leetcode 796. Rotate String | 796. 旋转字符串(KMP)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 796. Rotate String | 796. 旋转字符串(KMP)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/rotate-string/
題解
左神講的 KMP
class Solution {public boolean rotateString(String s, String goal) {if (s.length() != goal.length()) return false;return getIndexOf(s + s, goal) >= 0;}// KMPpublic static int getIndexOf(String s1, String s2) {if (s1 == null || s2 == null || s2.length() < 1 || s1.length() < s2.length()) {return -1;}char[] str1 = s1.toCharArray();char[] str2 = s2.toCharArray();int x = 0;int y = 0;// O(M) m <= nint[] next = getNextArray(str2);// O(N)while (x < str1.length && y < str2.length) {if (str1[x] == str2[y]) {x++;y++;} else if (next[y] == -1) { // y == 0x++;} else {y = next[y];}}return y == str2.length ? x - y : -1;}public static int[] getNextArray(char[] str2) {if (str2.length == 1) {return new int[]{-1};}int[] next = new int[str2.length];next[0] = -1;next[1] = 0;int i = 2; // 目前在哪個位置上求next數(shù)組的值int cn = 0; // 當前是哪個位置的值再和i-1位置的字符比較while (i < next.length) {if (str2[i - 1] == str2[cn]) { // 配成功的時候next[i++] = ++cn;} else if (cn > 0) {cn = next[cn];} else {next[i++] = 0;}}return next;} }總結
以上是生活随笔為你收集整理的leetcode 796. Rotate String | 796. 旋转字符串(KMP)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 638. Shoppi
- 下一篇: leetcode 1008. Const