<30>——Substring with Concatenation of All Words

30、Substring with Concatenation of All Words

子字符串连接的单词

现有一组长度相等的字符串words,要在原字符串中找出正好包含words中所有字符串的子字符串的起始位置。 

例子: 

输入: s = “barfoothefoobarman”, words = [“foo”, “bar”] 

输出: [0, 9]

分析:

(unordered_map<关键字,值>无序map类型)

1.这道题是寻找子字符串的深化版本,寻找的子字符串是由多个等长的字符串连接在一起的,难点就在于子字符串之间没有先后顺序。

2.就是我们需要确保每一个子字符串都只出现了一次,所以我们需要两个unordered_map<string,int>来存储字符串和他的出现次数,一个做为对比模板,一个做为查找计数。

3.迭代原字符串,每当找到一个同words中的字符串时,就进入循环类比接下来同样长度的字符串中是否与words相同且不重复,达成则记录迭代,否则break。

代码:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        unordered_map<string,int> compare;//比较模板
        for(string w:words)
            compare[w]++;
        int n=s.length(),num=words.size(),len=words[0].length();
        vector<int> res;
        for(int i=0;i<=n-num*len+1;i++)
        {
            unordered_map<string,int>counts;//计数
            int j=0;
            for(;j<num;j++)
            {
                string word=s.substr(i+j*len,len);//复制
                if(compare.find(word)!=compare.end())
                {
                    counts[word]++;
                    if(counts[word]>compare[word])
                        break;
                }
                else break;
            }  
            if(j==num)res.push_back(i);
        }
        return res;
    }
};




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值