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

Solution:
思路:每个word的长度是一样的,那么可以依次比较,每次s.substring(i,n-i);
然后比较word_num(words的个数) * per_num(每个word的长度)。每次读一个per_num,如果在map里存在了,则在后面词频+1,如果超过了标准的map里存放的词频则break。总的来说就是一个词频统计的过程。

vector<int> findSubstring(string s, vector<string>& words)
    {
        map<string,int> word_term;
        map<string,int> temp_term;
        map<string,int>::iterator word_it;
        int word_num = words.size();
        int per_num = words[0].length();
        int  n = s.size();
        vector<int> arr;
        if(word_num == 0 || n == 0)
            return arr;
        for(int i =0;i<words.size();i++)
        {
            word_it = word_term.find(words[i]);
            if(word_it == word_term.end())
            {
                word_term.insert(pair<string,int>(words[i],1));
            }
            else
            {
                word_it->second ++;
            }
        }
        int  i,j,pos;
        string temp_s;

        for(i = 0;i<n;i++)
        {
            temp_s = s.substr(i,n-i);
            if(s.size() < word_num * per_num)
                break;

            for(j=0;j<word_num;j++)
            {
                pos = per_num *j;
                string key_s  = temp_s.substr(pos,per_num);
                temp_term[key_s]++;
                if(temp_term[key_s] > word_term[key_s])
                    break;
            }
            temp_term.clear();
            if(j == word_num)
            {
                arr.push_back(i);
            }
        }

        return arr;
    }

你可能感兴趣的:(LeetCode)