LEETCODE: Substring with Concatenation of All Words

来源:互联网 发布:平板怎么登录淘宝卖家 编辑:程序博客网 时间:2024/06/06 02:20
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).



class Solution {public:   vector<int> findSubstring(string S, vector<string> &L) {      int lengthL = L[0].length() * L.size();      vector<int> results;      int gap = S.length() - lengthL;// We do not want to waste time,                                      // so if the remain is less than the total, no need to calculate.      if(gap < 0)         return results;      map<string, int> word_count; // One word may appears more than one time.      for (int ii = 0; ii < L.size(); ++ii) {            ++word_count[L[ii]];      }             map<string, int> counting;      for(int ii = 0; ii <= gap; ii ++) { // Loop through S from 0 to gap.         counting.clear();         int jj = ii;         for(; jj < ii + lengthL; jj += L[0].length()) { // Process string from ii to ii + lengthL.            string sub = S.substr(jj, L[0].length());            if(word_count.find(sub) != word_count.end()) {               ++counting[sub];                              if(counting[sub] > word_count[sub]) {                   break;               }            }            else {                break;            }         }         if(jj == ii + lengthL) {            results.push_back(ii);         }      }      return results;   }};


0 0
原创粉丝点击