1. 程式人生 > 實用技巧 >LeetCode 30. 串聯所有單詞的子串

LeetCode 30. 串聯所有單詞的子串

題目描述

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

示例1:

輸入:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
輸出:[0,9]
解釋:
從索引 0 和 9 開始的子串分別是 "barfoo" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。

示例2:

輸入:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
輸出:[]

來源:力扣(LeetCode)
連結:[https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words](https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words

思路解析

使用一個雜湊表來儲存 words中所有單次出現的次數,然後比較 s的子串所構成的雜湊表與 words生成的雜湊表,若相等,記錄起點下標。

程式碼實現

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> result;
        if(words.empty() || s.length() == 0) return result;
        // Construct map
        unordered_map<string, int> word_map;
        for(auto word : words) word_map[word]++;
        // Init variables
        int word_length = words[0].length();
        int str_length = word_length * words.size();     
        int max_start = s.length() - str_length + 1;
        // Traverse the string and compare the hash map
        for(int i = 0; i < max_start; i++) {
            unordered_map<string, int> temp_map = word_map;
            for(int j = 0; j < words.size(); j++) {
                string temp_word = s.substr(i + j * word_length, word_length);
                if(temp_map[temp_word] > 0) {
                    temp_map[temp_word]--;
                    if(temp_map[temp_word] == 0)
                        temp_map.erase(temp_word);
                }
                else
                    break;
            }
            if(temp_map.empty())
                result.push_back(i);
        }
        return result;
    }
};