Leetcode Substring with Concatenation of All Words

OpenSoucre發表於2014-07-04

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

題目意思: 輸入字串S和列表L,L含有一組長度相同的單詞。找出所有子串的開始下標,該子串由L的所有單詞拼接而成,而且沒有夾雜其他字元

解題思路是:

  從原串S的第一個字元開始,取長度為L的元素個數乘以L裡單詞的長度,然後判斷該串是否僅僅含了L得所有單詞。

  將子串拆分成多個長度和L單詞長度一致的單詞,然後根據hash_map來匹配子串的單詞

    如果單詞匹配成功,則匹配數加1;

    如果最後的匹配數等同於L的元素的個數,那麼該串包含了L得所有單詞,而且把該串的開始位置放入結果集中,繼續考察S的下一個字元開始的字串情況。

  下面程式碼不知為什麼會超時

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        vector<int> res;
        int l_len = L.size(), sub_l_len = L[0].length();
        int subLen = l_len * sub_l_len;
        unordered_map<string, int> hash_map;
        for(int i = 0 ; i <  l_len; ++ i ) hash_map[L[i]]++;
        for(int i = 0 ; i < S.length()-subLen+1; ++i){
            string sub = S.substr(i,subLen);
            int cnt = 0;
            unordered_map<string,int> cpHashMap(hash_map);
            for(int j = 0; j < l_len; ++ j){
                string word = sub.substr(j*sub_l_len,sub_l_len);
                if(cpHashMap.find(word)==cpHashMap.end() || cpHashMap[word] == 0) break;
                else{
                    cpHashMap[word]--;
                    cnt++;
                }
            }
            if(cnt == l_len) res.push_back(i);
        }
        return res;
    }
};
View Code

對上面程式碼進行優化,減少了hash_map的拷貝

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        vector<int> res;
        int l_len = L.size(), sub_l_len = L[0].length();
        int subLen = l_len * sub_l_len;
        unordered_map<string, int> hash_map,curHashMap;
        for(int i = 0 ; i <  l_len; ++ i ) hash_map[L[i]]++;
        for(int i = 0 ; i < S.length()-subLen+1; ++i){
            string sub = S.substr(i,subLen);
            int cnt = 0;
            curHashMap.clear();
            for(int j = 0; j < l_len; ++ j){
                string word = sub.substr(j*sub_l_len,sub_l_len);
                if(hash_map.find(word) ==hash_map.end()) break;
                curHashMap[word]++;
                if(curHashMap[word] > hash_map[word]) break;
                cnt++;
            }
            if(cnt == l_len) res.push_back(i);
        }
        return res;
    }
};

 

 

 

相關文章