日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

leetcode 796. Rotate String | 796. 旋转字符串(KMP)

發(fā)布時間:2024/2/28 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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; // 當(dāng)前是哪個位置的值再和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;} }

總結(jié)

以上是生活随笔為你收集整理的leetcode 796. Rotate String | 796. 旋转字符串(KMP)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。