题目
一个字符串s,如果把s前面任意部分移到后面形成的字符串叫s 的旋转词。给定字符串s1, s2,判断s1, s2是否互为旋转词。
思路
如果s1, s2长度不同,一定不互为旋转词;
‘123’, ‘231’互为旋转词,可以发现若s2后面再拼一个s2得到’23[123]1’,s1一定是s2s2的字串;
实现
def is_rotation1(a, b):
if a is None or b is None or len(a) != len(b):
return False
return a in b*2
def is_rotation2(a, b):
return a and b and len(a) == len(b) and a in b*2
测试
def test_is_rotation():
assert(is_rotation1('cdab', 'abcd') is True)
assert(is_rotation1('1ab2', 'ab12') is False)
assert(is_rotation1('2ab1', 'ab12') is True)
assert(is_rotation1('1234', '12341234') is False)
assert(is_rotation2('cdab', 'abcd') is True)
assert(is_rotation2('1ab2', 'ab12') is False)
assert(is_rotation2('2ab1', 'ab12') is True)
assert(is_rotation2('1234', '12341234') is False)
if __name__ == '__main__':
test_is_rotation()
测试2
发现牛客网可以对本书一些题目做测试…
判断两个词是否互为旋转词