作者JerryChungYC (JerryChung)
標題Re: [閒聊] 每日leetcode
時間2024-11-03 12:37:52
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了 嗚哇哇哇哇
--
※ 發信站: 批踢踢實業坊(web-ptt.org.tw), 來自: 114.45.55.73 (臺灣)
※ 文章網址: https://web-ptt.org.tw/Marginalman/M.1730608674.A.B6B