1.Leetcode28
问题描述:
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
代码解析:
int strStr(string haystack, string needle) {
// 获取模式串的next数组
int* next = getNext(needle);
//j代表已经匹配到模式串中的哪个下标
int j = -1;
for (int i = 0; haystack[i]; i++) {
while (j != -1 && haystack[i] != needle[j + 1])j = next[j];
if (haystack[i] == needle[j + 1])j += 1;
if (needle[j + 1] == '\0')return i - needle.size() + 1;
}
return -1;
}
int* getNext(string t) {
int tlen = t.size();
int* next = new int[tlen];
next[0] = -1;
int j = -1;
for (int i = 1; i < tlen; i++) {
while (j != -1 && t[i] != t[j + 1])j = next[j];
if (t[i] == t[j + 1])j += 1;
next[i] = j;
}
return next;
}
2.Leetcode459
问题描述:
给定一个非空的字符串 s
,检查是否可以通过由它的一个子串重复多次构成。
代码解析:
bool repeatedSubstringPattern(string s) {
int n=s.size();
//至少存在两个相同的字串,因此枚举到长度为一半的子串截止
for(int i=1;i*2<=n;i++){
//长度为母串长度的倍数才能满足条件
if(n%i==0){
bool k=true;
for(int j=i;j<n;j++){
if(s[j]!=s[j-i]){
k=false;break;
}
}
if(k)return true;
}
}
return false;
}