日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 686. Repeated String Match | 686. 重复叠加字符串匹配(KMP)

發(fā)布時(shí)間:2024/2/28 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 686. Repeated String Match | 686. 重复叠加字符串匹配(KMP) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目

https://leetcode.com/problems/repeated-string-match/

題解

套了 KMP 模板,O(n) 復(fù)雜度。分析如下。

class Solution {public int repeatedStringMatch(String a, String b) {int repeatedTimes = Math.max((int) Math.ceil((float) 2 * b.length() / a.length()), 2);int index = indexOf(a.repeat(repeatedTimes), b);if (index == -1) return -1;return (int) Math.ceil((float) (index + b.length()) / a.length());}// KMP, find index of s2 from s1public static int indexOf(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 = nextArray(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[] nextArray(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; // 目前在哪個(gè)位置上求next數(shù)組的值int cn = 0; // 當(dāng)前是哪個(gè)位置的值再和i-1位置的字符比較while (i < next.length) {if (str2[i - 1] == str2[cn]) { // 配成功的時(shí)候next[i++] = ++cn;} else if (cn > 0) {cn = next[cn];} else {next[i++] = 0;}}return next;} }

總結(jié)

以上是生活随笔為你收集整理的leetcode 686. Repeated String Match | 686. 重复叠加字符串匹配(KMP)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

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