Leetcode Substring with Concatenation of All Words

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;
    }
};
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3824935.html