LeetCode OJ:Substring with Concatenation of All Words

来源:互联网 发布:java c 编辑:程序博客网 时间:2024/06/13 11:34

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

算法思想:

暴力

class Solution {public:    vector<int> findSubstring(string S, vector<string> &L) {                map<string, int> words;            map<string, int> count;            vector<int> result;            int wordNum = L.size();            if (wordNum == 0) return result;            for (int i = 0; i < wordNum; ++i)                ++words[L[i]];                        int wordSize = L[0].size();            int slength = S.size();            for (int i = 0; i <= slength - wordSize*wordNum; ++i)            {                count.clear();                int j = 0;                for (; j < wordNum; ++j)                {                    string str = S.substr(i+j*wordSize, wordSize);                     if(words.find(str) == words.end())                          break;                      ++count[str];                      if(count[str] > words[str])                          break;                  }                if (j == wordNum) result.push_back(i);            }            return result;      }};



0 0