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).


[cpp]  view plain copy
  1. class Solution {  
  2. public:  
  3.     vector<int> findSubstring(string S, vector<string> &L) {  
  4.         map<string, int> words;  
  5.         map<string, int> curStr;  
  6.         for(int i = 0; i < L.size(); ++i)  
  7.             ++words[L.at(i)];  
  8.         int N = L.size();  
  9.         vector<int> ret;  
  10.         if(N <= 0)   return ret;  
  11.         int M = L.at(0).size();  
  12.         for(int i = 0; i <= (int)S.size()-N*M; ++i)  
  13.         {  
  14.             curStr.clear();  
  15.             int j = 0;  
  16.             for(j = 0; j < N; ++j)  
  17.             {  
  18.                 string w = S.substr(i+j*M, M);  
  19.                 if(words.find(w) == words.end())  
  20.                     break;  
  21.                 ++curStr[w];  
  22.                 if(curStr[w] > words[w])  
  23.                     break;  
  24.             }  
  25.             if(j == N)  ret.push_back(i);  
  26.         }  
  27.         return ret;  
  28.     }  
  29. };  

你可能感兴趣的:(LeetCode Substring with Concatenation of All Words)