【LeetCode】796. 旋轉字串
阿新 • • 發佈:2021-08-17
796. 旋轉字串
知識點:字串;KMP演算法;
題目描述
給定兩個字串, A和B。
A的旋轉操作就是將A 最左邊的字元移動到最右邊。例如, 若A = 'abcde',在移動一次之後結果就是'bcdea'。如果在若干次旋轉操作之後,A能變成B,那麼返回True。
示例
示例 1:
輸入: A = 'abcde', B = 'cdeab'
輸出: true
示例 2:
輸入: A = 'abcde', B = 'abced'
輸出: false
解法一:暴力法
依次後移依次比較
class Solution { public boolean rotateString(String s, String goal) { if(s.length() != goal.length()) return false; if(s.length() == 0) return true; search: for(int i = 0; i < s.length(); i++){ //旋轉的次數; for(int j = 0; j < goal.length(); j++){ if(s.charAt((i+j) % s.length())!= goal.charAt(j)){ continue search; //匹配不上直接比較下一次旋轉; } } return true; } return false; } }
解法二:API
其實A+A裡就包含了所有A進行旋轉的結果,所以只要判斷B是否是A的子串就可以了,而String類含有contains方法;
class Solution {
public boolean rotateString(String s, String goal) {
return (s.length() == goal.length()) && ((s+s).contains(goal));
}
}
解法三:KMP演算法
按照上面的分析,如果把A拓展成為A+A,那這道問題就變成了在A+A中是否含有B的子串,這是經典的字串匹配問題,最經典的當屬於KMP演算法。
class Solution { public boolean rotateString(String s, String goal) { int n = goal.length(); int[] next = buildNext(goal, n); if(s.length() != goal.length()) return false; int i = 0; int now = 0; String news = s+s; while(i < news.length()){ if(news.charAt(i) == goal.charAt(now)){ i++; now++; }else if(now != 0){ now = next[now-1]; }else{ i++; } if(now == goal.length()){ return true; } } return false; } private int[] buildNext(String str, int n){ int[] next = new int[n]; int now = 0; int i = 1; while(i < n){ if(str.charAt(i) == str.charAt(now)){ now++; next[i] = now; i++; }else if(now != 0){ now = next[now-1]; }else{ next[i] = 0; i++; } } return next; } }