面试金典09(Python)—— 字符串轮转(简单)

字符串轮转

概述:字符串轮转。给定两个字符串 s1 s2 ,请编写代码检查 s2 是否为 s1 旋转而成(比如, waterbottleerbottlewat 旋转后的字符串)。

输入:s1 = "waterbottle", s2 = "erbottlewat"
输出:True

输入:s1 = "aa", s2 = "aba"
输出:False

方法一:字符串检索

思路:轮转指的是,首字符转到末尾,依次转动。思路非常简单,直接用字符串检索加拼接,依次循环判断即可。需要注意的是,边界条件单独判断。

# 字符串检索
class Solution:
    def isFlipedString(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        if s1 == '' and s2 == '':
            return True
        for i in range(len(s1)):
            ans = (s1[i + 1:] + s1[:i + 1])
            if ans == s2:
                return True
            ans = ''
        return False

方法二:取模运算符

思路:用取模运算符,来模拟轮转指针。其余的思路基本一致,不再赘述。

# 取模运算符
class Solution:
    def isFlipedString(self, s1: str, s2: str) -> bool:
        n = len(s1)
        if n != len(s2):
            return False
        if s1 == '' and s2 == '':
            return True
        for i in range(n):
            for j in range(n):
                if s1[(i + j) % n] != s2[j]:
                    break
            else:
                return True
        return False

方法三:in 判断

思路:该算法非常巧妙!既然题目并不要求输出轮转的步骤,那么直接判断 s2 in (s1 + s1)  即可。

# in 判断
class Solution:
    def isFlipedString(self, s1: str, s2: str) -> bool:
        return len(s1) == len(s2) and s2 in (s1 + s1)

总结

这,这这不对吧,我看标签上明明写着简单啊!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值