96-Substring with Concatenation of All Words

-30. Substring with Concatenation of All Words My Submissions QuestionEditorial Solution
Total Accepted: 55346 Total Submissions: 264413 Difficulty: Hard
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).

题意:一句正常话中各个词(等长)的随机组合
判定是否在给定字符串中。
难度:高,需要考虑很多细节问题。。,需要考虑很多
test cases:
一开始以为s也是固定单词组合不可拆分,原来s是随机串

/*
test cases:
    //vector<string> vs={"bar","foo","the"};
    //res=s.findSubstring("barfoofoobarthefoobarman",vs);

    vector<string> vs={"a","b"};
    res=s.findSubstring("aaa",vs);

    //vector<string> vs={"fooo","barr","wing","ding","wing"};
//  res=s.findSubstring("lingmindraboofooowingdingbarrwingmonkeypoundcake",vs);

    "aaaaaaaaaaaa"
    "aa" "aa" "aa"
*/

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        int ws_n = words.size(),len=0;
        if(ws_n>0)len=words[0].size();
        int tlen=ws_n*len;  //整个words序列的长度
        map<string,int> wset,wet_o;
        for(string &s:words){             //将words的词存入map并计数
                if(wset.count(s)) ++wset[s]; 
                else wset[s]=1;
        }
        wet_o=wset;          //每次将map重置!!非常重要!!!
        int i=0,s_n=s.size();
        string tmp;  vector<int> res;
        while(i<=s_n-tlen){   //
            wset = wet_o;
            int list_end = i+tlen-1;  //每次移动到待找序列末尾
            int flag=-1;
            while(list_end>=i){
                tmp=s.substr(list_end-len+1,len); //每次取得一个word的长度
                if(!wset.count(tmp)){ flag=0;break; } //如果word不在map里面则跳出
                else {
                    if(wset[tmp]--==0){ flag=1;break; } //如果word在map里,却已经出现了该出现的次数
                    list_end = list_end-len;           //如果word在map里正常出现,则向前找前一个word
                }
            }
            if(flag==0||flag==1)++i;  //在定长tlen序列中非法出现,起始位置前移
            else res.push_back(i), ++i; //正常出现,保留起始位置
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值