Problem: Good String

Given a string S of length N, you have to tell whether it is good or not. A good string is one where the distance between every two adjacent character is exactly 1. Consider that the alphabets are arranged in cyclic manner from ‘a‘ to ‘z’. Hence, distance between any character ‘i’ and ‘j’ will be defined as minimum number of steps it takes ‘i’ to reach ‘j’. Here, character ‘i’ can start moving clockwise or anti-clockwise in order to reach at position where character ‘j’ is placed. Your task is simple, where you just need to print “YES” or “NO” (without quotes) depending on whether the given string is Good or not
Input:
First line of the input contains T denoting the number of test cases.Then T lines follow. Each line contains a string S.
Output:
Print  the answer for each testcase in a separate line.
Constraints:

1≤T≤50
1≤|S|≤50

Note: S contains only lowercase alphabetic characters
Input:
3
aaa
cbc
bcd

Output:
NO
YES
YES

Python 2.7

def is_perfect(s):
    """
        check if a string
        is a perfect sitrng
        s : a list of character
    """
    length = len(s)
    if length <= 1:
        return True
    for _ in range(1, length):
        if (s[_] == 'a' and s[_-1] == 'z') \
            or (s[_] == 'z' and s[_-1] == 'a'):
                continue
        if abs(ord(s[_])-ord(s[_-1])) != 1:
            return False
    else:
        return True

if __name__ == '__main__':
    t = input()
    for _ in range(t):
        s = list(raw_input().strip())
        print 'YES' if is_perfect(s) else 'NO'
Advertisements