【每日一题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 个赞

这个思路就很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

灰常有意思。

def rotateString( s: str, goal: str) -> bool:
    i=0
    tmp_s=list(s)
    tmp_g=list(goal)
    while i<=len(tmp_s):
        a=tmp_s[0]
        tmp_s.remove(a)  ##移除找到第一个元素,后面的不管
        tmp_s.append(a)
        i+=1
        return True if tmp_s==tmp_g else False




rotateString(s = "abcda", goal = "eaabcde")
def rotateString(s: str, goal: str) -> bool:
    n=1
    while n<len(s):
        s=s[1:]+s[0]
        if s==goal:
            return True
        n+=1
    return False

assert rotateString("abcde","cdeab")==True
assert rotateString("abcde","abced")==False