1. 程式人生 > >LeetCode 30 — Substring with Concatenation of All Words(與所有單詞相關聯的字串)

LeetCode 30 — Substring with Concatenation of All Words(與所有單詞相關聯的字串)

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:
Input:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoor” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = “wordgoodstudentgoodword”,
words = [“word”,“student”]
Output: []

翻譯

給定一個字串 s 和一些長度相同的單詞 words。在 s 中找出可以恰好串聯 words 中所有單詞的子串的起始位置。
注意子串要與 words 中的單詞完全匹配,中間不能有其他字元,但不需要考慮 words 中單詞串聯的順序。

示例 1:
輸入:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
輸出: [0,9]
解釋: 從索引 0 和 9 開始的子串分別是 “barfoor” 和 “foobar” 。
輸出的順序不重要, [9,0] 也是有效答案。
示例 2:
輸入:
s = “wordgoodstudentgoodword”,
words = [“word”,“student”]
輸出: []

分析
這題有個巧妙之處就在於words的長度是相同的,這其實大大降低了檢查的複雜度,因為我們可以拆分成若干個單詞字串來比對。

我的思路來源於別人的部落格:先將words轉化為字典,key為word,value為每個word在words裡出現的次數。然後在s中依次擷取長度等於words所有單詞長度總和的子串。再將字串拆分成若干個長度為每個word長度的子串。開始在字典裡匹配,每匹配一個就對應的value減一。遍歷結束時所有value都為0說明正好匹配。

結果是思路正確,提交超時。主要是因為當s足夠長的時候,擷取的子串太多了。所以優化方案是:可以先遍歷一遍s,擷取所有長度為每個word的長度的子串,找到只要匹配一個word的串的下標。進行整體匹配時只要從這些已經匹配了一個word的下標開始擷取。

c++實現

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if (words.size() == 0)
            return res;
        
        //將words轉化為字典
        vector<int> start;
        map<string,int>::iterator it;
        int word_len = words[0].length();
        int len = word_len*words.size();
        bool pipei = true;
        map<string,int> words_dict;
        map<string,int> copy;
        for (int i = 0; i < words.size(); i++)
        {
            words_dict[words[i]] += 1;
            copy[words[i]] += 1;
        }
        
        //剪枝優化
        for (int i = 0; i+word_len <= s.length(); i++)
        {
            string S = s.substr(i,word_len);
            for (it = copy.begin(); it != copy.end(); it++)
            {
                if (S == (*it).first)
                {
                    start.push_back(i);
                    break;
                }
            }
        }
        
        //程式主幹部分,將字串拆分匹配
        vector<int>::iterator itt;
        for (itt = start.begin(); itt != start.end() && *itt+len <= s.length(); itt++)
        {
            string S = s.substr(*itt,len);
            for (int j = 0; j < len/word_len; j++)
            {
                string tmp = S.substr(j*word_len,word_len);
                for (it = copy.begin(); it != copy.end(); it++)
                {
                    if ((*it).first == tmp)
                    {
                        (*it).second--;
                        break;
                    }
                }
            }
            for (it = copy.begin(); it != copy.end(); it++)
            {
                if ((*it).second != 0)
                {
                    pipei = false;
                    break;
                }
            }
            if (pipei)
                res.push_back(*itt);
            else
                pipei = true;
            copy = words_dict;
        }
        
        return res;
    }
};