标签:
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).
题目的意思是给你一个字符串,和一个字符串的数组,需要返回一个该字符串的索引组成的数组,返回的索引有如下性质:从每个索引开始,长度为L的字串需要精确包含字符串数组中的所有字符串(不多不少)。L 为字符串数组中所有字符串长度之和。
解决思路,使用一个map,键为字符串数组中的字符串,值为该字符串在字符串数组中出现的次数。遍历字符串s,寻找和字符串数组中的字符串相同的字串,找到后map中的值减一,否则重新初始化map,从下一个字符开始遍历。如果map中所有的值都为0,则找到了一个符合条件的子串,索引压入数组。
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 };
LeetCode 30 Substring with Concatenation of All Words
标签:
原文地址:http://www.cnblogs.com/yang-xiong/p/4949285.html