Leetcode 30. 与所有单词相关联的字串

利用map记录words字符串数组里每个字符串出现的次数,在s字符串里截取与word字符串数组里所有字符大小一致的字符串,并按word里每个字符串的大小存在map里,所有单词都在S中出现,且出现的次数和words中的次数一致 。

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
     vector<int> ans;
        ans.clear();
    map<string,int> wmap;
    map<string,int> smap;
        wmap.clear(),smap.clear();
        int wlen=words.size(),slen=s.size();
        if(wlen==0||slen==0) return ans;
        int perlen=words[0].size();
        if(perlen*wlen>slen) return ans;
        for(int i=0;i<wlen;++i)
            wmap[words[i]]++;
        for(int i=0;i+perlen*wlen-1<slen;++i)
        {
            int j=i;
            smap.clear();
            while(j<=i+perlen*wlen-1)
            {
                smap[s.substr(j,perlen)]++;
                if(wmap[s.substr(j,perlen)]<smap[s.substr(j,perlen)]) break;
                else j+=perlen;
                if(j>i+perlen*wlen-1)
                    ans.push_back(i);
            }
        }

猜你喜欢

转载自blog.csdn.net/qq_43387999/article/details/86509188