【一天一道LeetCode】#30. Substring with Concatenation of All Words

注:这道题之前跳过了,现在补回来


一天一道LeetCode系列

(一)题目

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 wordsexactly 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).

(二)解题

本题需要在s中找到一串子串,子串是words中的单词按一定顺序排列组成的。返回这个子串在s中的起始位置。
主要思路:由于要考虑words中的重复单词,需要用到multiset,加快查找速度
1、首先用multiset存放words中的所有单词
2、遍历s,如果找到words中的某个单词,就在multiset中删除,直到multiset为空,如果没有找到则继续往后查找
3、返回下标的集合

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        multiset<string> cnt;//用来存放words中的单词
        for (int i = 0; i < words.size(); i++)
        {
            cnt.insert(words[i]);//初始化
        }
        vector<int> ret;
        int lenw = words[0].length();
        int total = words.size() * lenw;
        int i, j;
        if (s.length() < total) return ret;
        for (i = 0; i <= s.length() - total;i++)
        {
            multiset<string> tempcnt = cnt;//拷贝一个副本
            for (j = i; j < s.length(); j += lenw)
            {
                string temp = s.substr(j, lenw);
                auto iter = tempcnt.find(temp);
                if (iter != tempcnt.end())//找到了
                {
                    tempcnt.erase(iter);//先删除该元素
                    if (tempcnt.empty()) {//为空代表找到了words中的所有单词按一定顺序排列的子串
                        ret.push_back(i);
                        break;
                    }
                }
                else {//没找到
                    break;
                }
            }
        }
        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值