https://leetcode.com/problems/rotate-string
796. Rotate String
给两个字串 s 跟 goal
如果 s 经过若干次 shift 之后 可以得到 goal 则回传 true
shift 代表把最左方的字符移动到最右方
Example 1:
Input: s = "abcde", goal = "cdeab"
Output: true
Example 2:
Input: s = "abcde", goal = "abced"
Output: false
Constraints:
1 <= s.length, goal.length <= 100
s 和 goal 只包含小写英文字母
思路:
逐次进行 shift 看是否跟 goal 相同
Python Code:
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
for i in range(len(s)):
if f'{s[i:]}{s[:i]}' == goal:
return True
return False
看其他答案才想到应该先判断两个字串的长度 (
练 JavaScript 的时候看到另一种解法 (不过下面还是 Python
return len(s) == len(goal) and goal in s * 2
剩我假日还要写leetcode了 呜哇哇哇哇