[python]LeetCode_796. Rotate String
文章目录
牽涉概念及時間紀錄
20220407 11:08-11:19 for 第一次
直接使用字串比較。
較佳解為使用KMP 演算法實作。
一、題目內容
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
if s = "abcde", it will be "bcdea" after one 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 and goal consist of lowercase English letters.
二、想法思路
1.直觀想法:
目的是要比較兩個str是否為右移相似,故直覺想到的就是字串比較。
這邊由於題目沒有說明兩者等長,故須先確認此狀況。
剩餘的即為迴圈確認即可。
時間複雜度 Worst O(N^2) 但常規上應為O(N)
空間複雜度 : O(1).
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
check = False
s_l = len(s)
goal_l = len(goal)
if s_l != goal_l:
return False
for num in range(s_l):
if s[0] == goal[num]:
num_tmp = (num+1)%s_l
while num_tmp != num:
if s[num_tmp-num] == goal[num_tmp]:
num_tmp = (num_tmp+1)%s_l
else:
break
if num_tmp == num:
check = True
break
if check is True:
return True
else:
return False
2.由於只有better than 66%故參考他人作法:
這邊是使用KMP,Knuth-Morris-Pratt字串尋找演算法
由於解釋較為複雜,直接附上此演算法之wiki解釋
KMP Algorithm
def nextGreatestLetter(letters: List[str], target: str) -> str:
def rotateString(self, A: str, B: str) -> bool:
if len(A) != len(B): return False
if len(A) == 0: return True
# capture length of strings
# then make both strings 1 indexed
N = len(A)
A = " " + A + A
B = " " + B
# calculate pi table, it captures the length of the
# longest prefix that is also the suffix
pi = [0] * (N+1)
left, pi[0] = -1, -1
for right in range(1, N+1):
while left >= 0 and B[left + 1] != B[right]:
left = pi[left]
left += 1
pi[right] = left
# do matching
j = 0
for i in range(1, (2*N)+1):
while j >= 0 and B[j+1] != A[i]:
j = pi[j]
j += 1
if j == N: return True
return False
总结
這題若要求速度,需熟練掌握KMP演算法的實作,但整體而言加速幅度不大。
此2方法在leetcode測資下時間為38與32ms。
有任何問題或錯誤都很歡迎留言討論,一起進步XD