1. 程式人生 > >LeetCode | Substring with Concatenation of All Words(連結所有單詞的子串)

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


題目解析:

這道題糾結了好久……由於對c++不熟悉,一直想用c來實現,結果就太麻煩了,不知道哪位大神用c成功實現,忘分享……

用c++的map就相當容易了,先將L中的字串在map中建立對映。然後S從前往後一次以某一個為起始字元判斷長度為l_size*word_size的連續字串是否都在map中。當然為了防止L中有重複的字串出現,另設一個counting,來記錄子串的個數,當個數超過word_count[word]的時候,也退出,遍歷S中的下一個字元。

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        int l_size = L.size();
        vector<int> res;
        if(l_size <= 0)
            return res;

        map<string,int> word_count; //記錄L字串中每一個元素出現的個數
        int word_size = L[0].size();
        for(int i = 0;i < l_size;i++)
            ++word_count[L[i]];
        map<string,int> counting;   //記錄查詢過程中的個數
        for(int i = 0;i <= (int)S.size()-l_size*word_size;i++){
            counting.clear();
            int j;
            for(j = 0;j < l_size;j++){
                string word = S.substr(i+j*word_size,word_size);
                if(word_count.find(word) != word_count.end()){
                    ++counting[word];
                    if(counting[word] > word_count[word])
                        break;
                }else
                    break;
            }
            if(j == l_size)
                res.push_back(i);
        }
        return res;
    }
};