[LeetCode]030-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).

Solution:
思路:每个word的长度是一样的,那么可以依次比较,每次s.substring(i,n-i);
然后比较word_num(words的个数) * per_num(每个word的长度)。每次读一个per_num,如果在map里存在了,则在后面词频+1,如果超过了标准的map里存放的词频则break。总的来说就是一个词频统计的过程。

vector<int> findSubstring(string s, vector<string>& words)
    {
        map<string,int> word_term;
        map<string,int> temp_term;
        map<string,int>::iterator word_it;
        int word_num = words.size();
        int per_num = words[0].length();
        int  n = s.size();
        vector<int> arr;
        if(word_num == 0 || n == 0)
            return arr;
        for(int i =0;i<words.size();i++)
        {
            word_it = word_term.find(words[i]);
            if(word_it == word_term.end())
            {
                word_term.insert(pair<string,int>(words[i],1));
            }
            else
            {
                word_it->second ++;
            }
        }
        int  i,j,pos;
        string temp_s;

        for(i = 0;i<n;i++)
        {
            temp_s = s.substr(i,n-i);
            if(s.size() < word_num * per_num)
                break;

            for(j=0;j<word_num;j++)
            {
                pos = per_num *j;
                string key_s  = temp_s.substr(pos,per_num);
                temp_term[key_s]++;
                if(temp_term[key_s] > word_term[key_s])
                    break;
            }
            temp_term.clear();
            if(j == word_num)
            {
                arr.push_back(i);
            }
        }

        return arr;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值