題目
https://leetcode.com/problems/repeated-string-match/
題解
套了 KMP 模板,O(n) 復雜度。分析如下。
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());}public 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;int[] next
= nextArray(str2
);while (x
< str1
.length
&& y
< str2
.length
) {if (str1
[x
] == str2
[y
]) {x
++;y
++;} else if (next
[y
] == -1) { x
++;} 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; int cn
= 0; 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 686. Repeated String Match | 686. 重复叠加字符串匹配(KMP)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。