首页 > 代码库 > leetcode 之 Substring with Concatenation of All Words

leetcode 之 Substring with Concatenation of All Words

Substring with Concatenation of All Words

 

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

思路:题目的意思是找到包含L中所有单词的起始位置,但是不能多,也不能少,要刚好包含L中的全部单词,而且相邻的两个开始位置还可以重叠,比如:S="aaa",L=[‘a‘,‘a‘],结果是[0,1]。具体方法和最短摘要有点类似,用need数组保存需要的所有单词,hasFind保存已经找到的单词,如果hasFind大于need,则该位置不满足,只有当两个数组完全相同时才满足。

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L)
    {
    	int totalWord = L.size(),wordLen = L[0].size(),i,j;
    	map<string,int> needWord;	
    	vector<int> res;
    	for (i = 0;i < totalWord;i++)needWord[L[i]]++;//统计需要的单词
    	for(i = 0;i + totalWord*wordLen <= S.size();i++)
    	{
    		map<string,int> hasFindWord;
    		for (j =0;j < totalWord;j++)//对于每一个单词
    		{
    			string sub = S.substr(i+j*wordLen,wordLen);//提取每一个可能的单词
    			map<string,int>::iterator iter = needWord.find(sub);
    			if(iter == needWord.end())break;
    			hasFindWord[sub]++;
    			if(hasFindWord[sub] > needWord[sub])break;
    		}
    		if(j == totalWord)	res.push_back(i);
    	}
    	return res;
    }

};


leetcode 之 Substring with Concatenation of All Words