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;
    }
};
posted @ 2020-11-02 20:59  行者橙子  阅读(141)  评论(0编辑  收藏  举报