码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[30]Substring with Concatenation of All Words

时间:2015-02-10 15:00:40      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
    vector<int> res;
    int len=L[0].size()*L.size();
    if (S.empty()||L.empty()||S.size()<len)return res;
    map<string,int> Lmap;
    map<string,int> temp;
    for (int i=0;i<L.size();i++)
        Lmap[L[i]]++;
    for (int i=0;i<=(int)S.size()-len;i++)
    {
        temp.clear();
        int j=i;
        for (;j<i+len;j+=L[0].size())
        {
            string word=S.substr(j,L[0].size());
            if (Lmap.find(word)==Lmap.end())
                break;
            temp[word]++;
            if (temp[word]>Lmap[word])
                break;
        }
        if (j==i+len)
            res.push_back(i);
    }
    return res;
    }
};

 

leetcode[30]Substring with Concatenation of All Words

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!