首页 > 技术文章 > [LeetCode]Substring with Concatenation of All Words

Rosanna 2013-11-26 21:16 原文

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

思考:两个map。判断单词是否存在,出现次数是否相同。

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        vector<int> res;
        map<string,int> words;
        map<string,int> visited;
        map<string,int>::iterator iter1,iter2;
        int i,j;
        int len=L[0].size();
        if(S.size()<L.size()*len) return res;
        for(i=0;i<L.size();i++) words[L[i]]++;
        for(i=0;i<=S.size()-L.size()*len;i++)
        {
            visited.clear();
            for(j=i;j<=S.size()-len;j=j+len)
            {
                string temp=S.substr(j,len);
                iter1=words.find(temp);
                iter2=visited.find(temp);
                if(iter1==words.end()) break;
                if(iter1->second<=iter2->second) break;
                visited[temp]++;
            }
            if(words==visited) res.push_back(i);
        }
        return res;
    }
};

  

推荐阅读