【发布时间】:2019-11-11 03:22:22
【问题描述】:
我很难理解为什么 Leetcode 的重复字符串匹配的解决方案只能达到 q + 1 次 A 重复(如果 A.length()
我阅读了其他 StackOverflow 解决方案以及 Leetcode 讨论页面,但我仍然无法完全理解该解决方案。
算法解释为:
Imagine we wrote S = A+A+A+.... If B is to be a substring of S, we
only need to check whether some S[0:], S[1:], ..., S[len(A) - 1:]
starts with B, as S is long enough to contain B, and S has period
at most len(A).
Now, suppose q is the least number for which len(B) <= len(A * q).
We only need to check whether B is a substring of A * q or A *
(q+1). If we try k < q, then B has larger length than A * q and
therefore can't be a substring. When k = q+1, A * k is already big
enough to try all positions for B; namely, A[i:i+len(B)] == B for i
= 0, 1, ..., len(A) - 1.
实现如下:
class Solution {
public int repeatedStringMatch(String A, String B) {
int q = 1;
StringBuilder S = new StringBuilder(A);
for (; S.length() < B.length(); q++) S.append(A);
if (S.indexOf(B) >= 0) return q;
if (S.append(A).indexOf(B) >= 0) return q+1;
return -1;
}
}
我知道当 A.length()
我的直觉是,在 A 重复若干次之后,就会建立一个模式,如果 B 不属于该模式/字符序列,那么无论你重复 A 多少次,B 都不会是重复 A 的子串。
但是,我只是不知道为什么它必须是与 B 的长度相匹配的副本数,或者在 A.length() = B.length() 之后添加的另外 1 个副本。
如果有人能为我解决这个困惑,将不胜感激。谢谢。
【问题讨论】:
标签: java string stringbuilder mod