串聯所有單詞的字串題解

串聯所有單詞的字串題解

有單詞串聯形成的子串的起始位置。

注意子串要與 words 中的單詞完全匹配,中間不能有其他字符,但不需要考慮 words 中單詞串聯的順序。
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
輸出:[0,9]

題解:
暴力就不考慮了,我第一種方法是,破產版的滑動窗口,每次滑動一個字符,用兩個map<string,int>一個dict存words,一個tmp存當前滑動窗的單詞。然後確定tmp的單詞對應匹配數是否在dict可以找到,挨個由於words的單詞長度都一樣,我想直接每次跳length_words進行匹配,顯然會丟結果。而且效果真的丟人。提交裏空間和時間都是倒數5%。嘿嘿,把我都氣笑了。
看了前面的代碼,頓悟,滑動窗口的正確姿勢。
滑動每次肯定是要按leng_word來滑動的,同時採用leng_word次外部循環確保不漏情況。爲什麼是leng_word次呢?既然是找子串,而且子串長度必然是leng_word的倍數,則外部循環只需按照leng_word的餘數作爲起始即可。
前者和後者時間複雜度分析分別是O(N2),O(mn)m=leng_word,後者避免了很多不必要的計算。
貼代碼:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int>res;
        unsigned int length=words.size();
        if(s.empty()||words.empty())return res;
        unsigned int ea_leng=words[0].size();
        if(!ea_leng)return res;
        unsigned int wins=ea_leng*length;
        
        unordered_map<string,int> dict;
        for (auto &a:words)++dict[a];
        
        if (s.size()<wins)
            return res;
        unsigned int s_leng=s.size();
        //滑動窗口思想
        unsigned int st,ed;
        st=0;ed=0;
        for(int i=0;i<ea_leng;i++)
        {
            unordered_map<string,int> temp;
            st=i;
            ed=st;
            while(ed+ea_leng<=s_leng)
            {
                string bs=s.substr(ed,ea_leng);
                ed+=ea_leng;
                if(dict.find(bs)==dict.end())
                {
                    st=ed;
                    temp.clear();
                }
                else
                {
                    ++temp[bs];
                    if(temp[bs]>dict[bs])
                    {
                        while(temp[bs]>dict[bs])
                        {
                            string buf=s.substr(st,ea_leng);
                            --temp[buf];
                            st+=ea_leng;
                        }
                    }
                    if(ed-st==wins)
                        res.push_back(st);
                }
            }
        }
        return res;
    }
};

第一名是8ms,而且方法很獨特,明天看看,再另外分析。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章