Re: [閒聊] 每日leetcode
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/11/03 12:37)推噓1(1推 0噓 0→)留言1則, 1人參與討論串1070/1548 (看更多)
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了 嗚哇哇哇哇
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.55.73 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1730608674.A.B6B.html
推
11/03 12:40,
1年前
, 1F
11/03 12:40, 1F
討論串 (同標題文章)
完整討論串 (本文為第 1070 之 1548 篇):