LeetCode OJ 之 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).

给一个字符串S和一串单词L,L中所有的单词有相同的长度。在S中找出所有的符合条件的子串的开始下标,这里的符合条件的子串是指由L中的所有单词组成,并且没有间隔,无序。

思路:

用哈希表存储L中的单词以及出现的次数,然后在S中取一个窗口,窗口大小为L[0].size() * L.size() ,窗口中的字符串每次取L[0].size() 长度的子串在哈希表中查找。如果窗口中的子串都能在哈希表中找到,则说明找到符合条件的,记录下来。

代码:

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) 
    {
        vector<int> result;
        if(L.empty())
            return result;
        map<string , int> words;//哈希表,存储L中对应单词出现的次数
        int wordLen = L[0].size();
        int wordNum = L.size();
        int len = wordLen * wordNum;
        if(S.size() < len)
            return result;
        for(int i = 0 ; i < L.size() ; i++)
            words[L[i]]++;
        for(int i = 0 ; i <= S.size() - len ; i++)
        {
            map<string , int> curWords;//存储已经查找到的单词以及出现的次数,主要用于判断是否找到重复的单词
            int j = i;
            for( ; j < i+len ; j += wordLen)
            {
                string tmp = S.substr(j,wordLen);
                if(words.find(tmp) == words.end())  //在words中没有发现,则直接中断当前循环
                    break;
                curWords[tmp]++;//否则,在curWords中次数+1
                if(curWords[tmp] > words[tmp])  
                    break;
            }
            if(j == i+len)
                result.push_back(i);
        }
        return result;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值