LeetCode 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 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 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM