leetcode 30. Substring with Concatenation of All Words

来源:互联网 发布:天津流氓 知乎 编辑:程序博客网 时间:2024/05/29 02:08

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 wordsexactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].

(order does not matter).

题目分析:给定字符串s,和字符串数组words,字符串数组中的字符串长度相等,返回由words中的字符串联,且每个字符串只出现一次的字符串s1在s中首次出现的下标。

解答分析:

1. 将words送入map<string, int> word;

2. 循环遍历,取s的部分子串s2;

3. 检验s2是否能由words组成。

实现代码:

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


vector<int> output;
int slen=s.size();
int wslen=words.size();
//考虑空数组的情况
if(!slen||!wslen)
return output;
int wlen=words[0].length();
map<string, int> word;
map<string, int> current;
//将worlds数组推入map容器中
for(vector<string>::iterator k=words.begin() ; k!=words.end(); ++k)
word[*k]++;
for(int i=0; i+wslen*wlen<=slen; i++)
{
current.clear();
int j=0;
for(j=0; j<wslen; j++)
{
string temp=s.substr(i+j*wlen, wlen);
if(word.find(temp)==word.end())
break;
++current[temp];
if(current[temp]>word[temp])
break;
}
if(j==wslen)
output.push_back(i);
}
return output;

}
};

0 0