leetcode_32 Substring with Concatenation of All Words

161 篇文章 0 订阅

题目:串联所有单词的子串

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 "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
Output: []

题目大意:给出单词列表,所有单词的长度相同,这些所有单词可能组成的字符串,在字符串s中出现的可能位置

原理解析:

I think the following code is self-explanatory enough. We use an unordered_map<string, int> counts to record the expected times of each word and another unordered_map<string, int> seen to record the times we have seen. Then we check for every possible position of i. Once we meet an unexpected word or the times of some word is larger than its expected times, we stop the check. If we finish the check successfully, push i to the result indexes.   我们用一个hashmap来记录words中的单词,及单词出现的次数(每个单词长度wlen,一共有n个单词,则子串的长度为wlen*n)。然后用另一个hashmap来记录相同长度(wlen*n长度)的子串中,子串是从字符串s的0位置开始,长度为 wlen*n的字符串, 每个单词(每个wlen长度为一个单词)及单词出现的次数,同时判断单词是否在前一个hashmap中出现,如果没有,则进入下一个循环。如果出现过,则记录在hashmap中,记录完之后,判断记录进的个数比前一个hashmap记录单词的个数大,如果大,就进入下一个循环。否则继续判断下一个单词,如果因大于单词个数n循环退出,说明,n个单词都在hashmap中出现过,且个数不超过,则个数相等,则该子串是要找的子串,记录此时的循环变量i,然后i++,在进行下一个子串的判断,直至 (int) s.size() - wlen*n 为最后一个子串的首位。

注意:s.size()是无符号整数,减去一个比自己大的数字,会出错。

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if(s.empty() || words.empty())
            return res;
        unordered_map<string,int> word_cnt;
        for(int i = 0; i < words.size(); i++)
        {
            word_cnt[words[i]]++;
        }
        int wlen = words[0].length();
        int n = words.size();
        int sublen = wlen * n;
        for(int i = 0; i <= (int)s.size() - sublen;i++)
        {
            unordered_map<string,int> str_cnt;
            int j = 0;
            for(j = 0;j < n; j++)
            {
                string str = s.substr(i + j*wlen,wlen);
                if(!word_cnt.count(str))    break;
                str_cnt[str]++;
                if(str_cnt[str] > word_cnt[str])    break;
            }
            if(j == n)
                res.push_back(i);    
        }
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值