LC.P686[重复叠加字符串匹配]

题目描述

给定两个字符串 ab,寻找重复叠加字符串 a 的最小次数,使得字符串 b 成为叠加后的字符串 a 的子串,如果不存在则返回 -1

注意:字符串 "abc" 重复叠加 0 次是 "",重复叠加 1 次是 "abc",重复叠加 2 次是 "abcabc"

示例1

输入:a = “abcd”, b = “cdabcdab”
输出:3
解释:a 重复叠加三遍后为 “abcdabcdabcd”, 此时 b 是其子串。

示例2

输入:a = “a”, b = “aa”
输出:2

提示:

  • 1 <= a.length <= 104
  • 1 <= b.length <= 104
  • ab 由小写英文字母组成

方法一:KMP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int repeatedStringMatch(String a, String b) {
StringBuilder builder = new StringBuilder();
int ans = 0, n = a.length(), m = b.length();
while (builder.length() < m) {
builder.append(a);
++ans;
}
builder.append(a);
int index = strStr(builder.toString(), b);
if (index == -1) return -1;
return index + m > n * ans ? ans + 1 : ans;
}

// LC
private int strStr(String ss, String pp) {
int n = ss.length(), m = pp.length();
ss = " " + ss;
pp = " " + pp;
char[] s = ss.toCharArray(), p = pp.toCharArray();
int[] next = new int[m + 1];
for (int i = 1, j = 0; i < m; ) {
if (j == 0 || p[i] == p[j]) {
++i;
++j;
next[i] = j;
} else {
j = next[j];
}
}
int i = 1, j = 1;
while (i <= n && j <= m) {
if (j == 0 || s[i] == p[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j > m) return i - m - 1;
else return -1;
}
}