LeetCode 30: Substring with Concatenation of All Words

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.

For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

解题思路

使用一个 Hash Table 存放 words 中的单词(记为 wordMap),其中 key 为单词, value 为单词出现的次数。

枚举符合条件的子串可能的起始位置 i 。首先获得以 s[i] 为起点的子串的第一个单词;然后查看在 wordMap 中是存在这个单词:如果不处在,指针 i 直接后移匹配下一个位置开始的子串;如果存在,我们把这个单词加入到一个新的 Hash Table(记为 curMap) 中,同时递增该单词出现的次数,然后判断这个单词的出现次数是否小于等于 wordMap 中的出现次数,如果大于说明匹配失败,指针 i 后移匹配下一个位置开始的子串;如果从 i 位置开始我们成功匹配了 words.size() 个单词则记录 i

代码如下:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        int wordNum = words.size();
        int wordLen = words[0].size();

        unordered_map<string, int> wordMap;
        for (int i = 0; i< wordNum; ++i) {
            wordMap[words[i]]++;
        }

        vector<int> result;
        int end = s.size() - wordNum * wordLen;
        for (int i = 0; i <= end; ++i) {
            int j;
            unordered_map<string, int> curMap;

            for (j = 0; j < wordNum; ++j) {
                string word = s.substr(i+j*wordLen, wordLen);

                if (wordMap.find(word) == wordMap.end()) break;

                curMap[word]++;

                if (curMap[word] > wordMap[word]) break;
            }

            if (j == wordNum) {
                result.push_back(i);
            }
        }

        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值