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.

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

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

题意

给一个字符串String和一组字符串string_list,string_list中的所有字符串长度一致。在String中寻找所有子串s,要求s是string_list中所有字符串的组合(不要求按照string_list中字符串存放的顺序),返回满足要求的子串第一个字符在String中的位置的集合。

思路

用两个map来解决,第一个map存放string_lsit中的字符串和对应的数量,第二个map存放子串中找到的string_list和对应的数量。对原字符串String从头开始遍历,以string_list的字符串的长度为步长,检查步长范围内的子串是否在string_list中且第二个map存放该子串的数量是否不大于第一个map存放该子串的数量,如果是则下一个步长,如果否则进入String的下一个字符。

代码

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        map<string, int> words_map;
        int l = s.size(), num = words.size(), len = words[0].size();
        for(int i = 0; i < num; i++){
            words_map[words[i]]++;
        }
        for(int i = 0; i < l - num*len + 1; i++){
            map<string, int> finded;
            int j = 0;
            for( ; j < num; j++){
                string cur = s.substr(i + j*len, len);
                if(words_map.find(cur) != words_map.end()){
                    finded[cur]++;
                    if(finded[cur] > words_map[cur]) break;
                }
                else break;
            }
            if(j == num) 
                res.push_back(i);  
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值