0
点赞
收藏
分享

微信扫一扫

Substring with Concatenation of All Words 字符串操作 匹配的字串数

Sky飞羽 2023-02-17 阅读 95


Substring with Concatenation of All Words


You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words

For example, given:

s: ​​"barfoothefoobarman"​

words: ​​["foo", "bar"]​​You should return the indices: ​​[0,9]​​.

(order does not matter).

class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {


int wordLen=words.size();
vector<int> res;

if(wordLen<=0)
return res;

int wordSize=words[0].size();

int i,j;
map<string,int> wordCount;
//map统计每个单词出现
for(i=0;i<wordLen;i++)
wordCount[words[i]]++;

map<string,int> tmp;
int len=s.length();
// for(i=0;i<=s.length()-(wordLen*wordSize);i++) 刚开始s.length没有用int转换一直过不了
//改为i<=(int)s.length() 过了
for(i=0;i<=len-(wordLen*wordSize);i++)
{
tmp.clear();
for(j=0;j<wordLen;j++)
{
string str=s.substr(i+j*wordSize,wordSize);
if(wordCount.find(str)!=wordCount.end())
{
tmp[str]++;
if(tmp[str]>wordCount[str])
break;
}
else
break;
}
if(j==wordLen)
res.push_back(i);
}
return res;
}
};

举报

相关推荐

0 条评论