28、 找出字符串中第一个匹配项的下标
28.1 题目
28.2 分析
28.3 代码
class Solution {
public:
int strStr(string haystack, string needle) {
int n =haystack.size(),m=needle.size();
if(m==0){
return 0;
}
vector<int> pi(m);
for(int i=1,j=0;i<m;i++){
while(j>0&&needle[i]!=needle[j]){
j=pi[j-1];//如果p[j]!=p[i],将j指针指向前一位置的next数组对应的值,即j=next[j-1]
//循环至j==0或p[i]=p[j],如果j=0,p[i]和p[j]还是不想等,则next[i]=0;i后移,j不变
}
if(needle[i]==needle[j]){
j++;
}
pi[i]=j;
}
for(int i=0,j=0;i<n;i++){
while(j>0&&haystack[i]!=needle[j]){
j=pi[j-1];
}
if(haystack[i]==needle[j]){
j++;
}
if(j==m){
return i-m+1;
}
}
return -1;
}
};
30、 串联所有单词的子串
30.1 题目
30.2 分析
30.3 代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int ls=s.size();
int m=words.size();
int n=words[0].size();
vector<int> ans;
for(int i=0;i<n;i++){
map<string,int> diff;
for(int j=0;j<m;j++){
++diff[s.substr(i+j*n,n)];
}
for (string &word:words){
diff[word]-=1;
if(diff[word]==0)
{
diff.erase(word);
}
}
for(int start=i;start<ls-m*n+1;start+=n){
if(start!=i){
string word=s.substr(start+(m-1)*n,n);
diff[word]+=1;
if(diff[word]==0){
diff.erase(word);
}
word=s.substr(start-n,n);
diff[word]-=1;
if(diff[word]==0){
diff.erase(word);
}
}
if(diff.empty())
{
ans.push_back(start);
}
}
}
return ans;
}
};