30. Substring with Concatenation of All Words
30. 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 exactly 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).
解题思想就是用Map去统计,减少组合的耗时,空间换时间。这个用map的方式还是很常用的。
前几天有同学面网易问了个题目就是:给你两个无序数组,一个长度为m,一个长度为n,求用0(m+n)的时间复杂度下找出他们公共的子数组。
eg input [1,2,2,3,4] , [2,2,3,4] output [2,2,3,4]
思路也是用map换时间,只不过对于key = 2的这种重复值,它的val就用计数的方式。
这里给个别人C++的代码,因为js跑的话,老是超时,没办法。有js过的代码,希望大神能给我留言,或者私信我,求教。
1 class Solution { 2 public: 3 void initializeMap(map<string,int>& map, vector<string>& words){ 4 for(int i = 0 ;i< words.size();i++){//初始化map 5 if(map.count(words[i])==0){ 6 map[words[i]] = 1; 7 } 8 else 9 map[words[i]] += 1; 10 } 11 } 12 vector<int> findSubstring(string s, vector<string>& words) { 13 map<string, int> mapOfVec; 14 int singleWordLen = words[0].length();//单个字符串长度 15 int wordsLen = words.size(); 16 int slen = s.length(); 17 int i,j,count; 18 bool countChanged = false;//判断是否改变过map中的值,如果没变则无需重新初始化 19 vector<int> result; 20 count = wordsLen; //一个计数器表示还需要找到的字串个数 21 if(wordsLen == 0 || slen ==0) return result; 22 initializeMap(mapOfVec,words); 23 for(i = 0; i<= slen-wordsLen*singleWordLen;i++){ 24 string subStr = s.substr(i,singleWordLen);// 取出字串 25 j = i; 26 while(mapOfVec.count(subStr)!=0 && mapOfVec[subStr]!=0 && j+singleWordLen<=slen){//当该字串存在于map中且值大于0,并且j不越界的情况下 27 mapOfVec[subStr] -=1; //值减1 28 count--; 29 countChanged = true; //改变了map的值 30 j=j+singleWordLen; 31 subStr = s.substr(j,singleWordLen); //下一个字串 32 if(mapOfVec.count(subStr)==0){ 33 break; 34 } 35 } 36 if(count==0){ 37 result.push_back(i); //找齐所有字符串数组中的字串后把该索引压入; 38 } 39 if(countChanged){ //若未找到而且改变了map的值需要重新初始化map和count 40 mapOfVec.clear(); 41 initializeMap(mapOfVec,words); 42 count = wordsLen; 43 countChanged = false; 44 } 45 } 46 return result; 47 48 } 49 };