【每日一题20220727】旋转字符串

:mage:‍给定两个字符串, s 和 goal。如果在若干次旋转操作之后,s 能变成 goal ,那么返回 true。

s 的旋转操作就是将 s 最左边的字符移动到最右边。

  • 例如, 若 s = ‘abcde’,在旋转一次之后结果就是’bcdea’。

示例 1:

输入: s = "abcde", goal = "cdeab"
输出: true

示例 2:

输入: s = "abcde", goal = "abced"
输出: false

提示:

  • 1 <= s.length, goal.length <= 100
  • s 和 goal 由小写英文字母组成

任务

编写一个函数, 执行上述操作

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
    # your code here

题目难度:简单
题目来源:796. 旋转字符串 - 力扣(LeetCode)

:+1:

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        # your code here
        n = len(s)
        while n > 0:
            round_result = s[1:] + s[0]
            if round_result == goal:
                return True
            s = round_result
            n -= 1
        return False

1 Like

这个思路就很nice,属实没想到 :joy:

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        l_s = list(s)
        last = l_s[-1]
        l_g = list(goal)
        while l_s[0] != last:
            a = l_s.pop(0)
            l_s.append(a)
            if l_s == l_g:
                return True
        return False
    def rotateString(s: str, goal: str) -> bool:
        if s == goal:
            return True
        for i in range(len(s)-1):
            s=s[1:]+s[0]
            if s == goal :
                return True
        return False

灰常有意思。

关闭