[LeetCode]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 words exactly 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).

找到匹配words的子串,采用hash map的方法。

采用两个hash map对比可以确定是否是子串。

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        int wordlen = words[0].size();
        int strlen = s.size();
        vector<int> result;
        map<string,int> temp;
        map<string,int> Count;
        if(strlen < wordlen*words.size())
            return result;
        for(int i=0;i<words.size();++i){
            ++temp[words[i]];
        }

        for(int i=0; i<=strlen-wordlen*words.size(); ++i){ //important bondary
            Count.clear(); //count the word we found
            int j=i;
            for(; j<i+wordlen*words.size(); j=j+wordlen){
                string se = s.substr(j,wordlen);
                if(temp.count(se) != 0){
                    ++Count[se];
                    if(Count[se]>temp[se])
                        break;
                }
                else break;
            }
            
            if(j>=i+wordlen*words.size()){
                result.push_back(i);
            }
            
        }
        return result;
    }
};


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