leetcode Substring with Concatenation of All Words

Substring with Concatenation of All Words

 

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

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

,算法思路,注意题目要求是每一个word都是一样长度的,我们采用像流水线一样的方法,比如一开始看0,下一个位置砍0+l,这样每次只需要看添加一个和删除一个字符串对整个数组的影响。用一个c来记录m个长度为l的字串有多少个在字典L中(准确说不是字典,因为有重复),用另外一个变量count来记录有多少个重复,多个重复算是只有一个重复,当没有重复并且有m个单词的时候,算是全部都包含了。

class Solution {

public:
    vector<int> findSubstring(string S, vector<string> &L) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<int> ans;
        if(S.size()==0)return ans;
        int m = L.size();
        if(m==0)return ans;
        int l = L[0].size();
        if(l==0)return ans;
        if(m*l>S.size())return ans;
        map<string,int >mp;
         for(int j = 0;j<m;j++)mp[L[j]]++;
        for(int i = 0;i<l;i++){
            if(i+m*l>S.size())break;
            map<string,int>  mp1(mp);//记录还有多少个没有匹配到
            int count = 0;//记录多少个单词出现重复,相同单词重复次数为1
            int c = 0;//记录读入m个单词多少个在List中
            for(int k = 0;k<m-1;k++){
                string str = S.substr(i+k*l,l);
                if(mp1.find(str)!=mp1.end()){
                    mp1[str]--;
                    if(mp1[str]==-1)count++;
                    c++;
                }
            }
            for(int st = i;st+l*m<=S.size();st+=l){
                string str = S.substr(st+(m-1)*l,l);
                if(mp1.find(str)!=mp1.end()){
                    mp1[str]--;
                    if(mp1[str]==-1)count++;
                    c++;
                }
                if(c==m && count==0){
                    ans.push_back(st);
                }
                str = S.substr(st,l);
                if(mp1.find(str)!=mp1.end()){
                    c--;
                    mp1[str]++;
                    if(mp1[str]==0)count--;
                }
            }
        }
        return ans;
        
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值