2021-01-03 Python百日打卡学习自【夸可编程】

给定2个字符串str1,str2,判断str1是否是str2 旋转后的字符串

例子:
None, 'hello' -> False
None, None -> False
'', '' -> False
'hello', 'ehllo' -> False
'hello', 'llohe' - > True

假设,字符串仅有ASCII字符组成
大小写敏感


def is_rotation(s1, s2):
    if s1 is None or s2 is None:
        return False
    if len(s1) != len(s2):
        return False
    if len(s1) == 0 or len(s2) == 0:
        return False
    # for i in range(1,len(s1) + 1): # 0, 1, 2
    #     # if s1[0:i] == s2[len(s2)-i:] and s1[i:] == s2[0:i]:
    #     # 若是旋转,必定有个位置,s1的左边等于s2的右边, 并且, s1的右边等于s2的左边
    #     if s1[:i] == s2[-i:] and s1[i:] == s2[:-i]:
    #         return True
    for i in range(len(s1)): #range是从0开始,但是没有-0 ,所以这个地方要加1
        if s1[:(i+1)] == s2[-(i+1):] and s1[(i+1):] == s2[:-(i+1)]:
            return True

    return False


# 如果是旋转而来,必定有包含关系
def another(s1, s2):
    if s1 is None or s2 is None:
        return False
    if len(s1) != len(s2):
        return False
    if s1 in s2+s2:
        return True
    return False


s1 = 'hello'
s2 = 'llohe'

print(is_rotation(s1, s2))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容