Leetcode_30 Substring with Concatenation of All Words

字符串匹配算法
本文介绍了一种使用双map数据结构来高效解决字符串匹配问题的方法,该方法适用于寻找由多个指定单词按任意顺序组成的子字符串在主字符串中的所有起始索引位置。

题目:

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.

Example 1:

Input:
s = “barfoothefoobarman”,
words = [“foo”,”bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoor” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
s = “wordgoodstudentgoodword”,
words = [“word”,”student”]
Output: []

题目意思:就是看word里面随便顺序连起来是不是出现过,然后将下标返回

解析:用map可以很好的解决这个问题,需要设置两个map,第一个map<string,int>word_count
记录每一个串在words中出现的次数 第二个map就是在遍历的时候需要记录words中每个单词出现的次数 map<string,int>counting; //记录在查找过程中的次数 其实就是在主串S中对words中的每个单词进行遍历,如果没有出现则直接跳出,出现了则counting[ss]++,因为ss出现的次数可能大于words_count[ss],那么也是不合理的。

代码:

#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
using namespace std;



vector<int> findSubstring(string s, vector<string>& words)
{
    vector<int>ans;
    if(s.length()==0||words.size()==0)  return ans;
    int i,j;
    int s_len = s.length();
    int l_size = words.size();
    map<string,int>word_count;  //记录每一个串在words中出现的次数
    for(i=0;i<l_size;i++)
       ++word_count[words[i]];
    int word_size = words[0].length();
    map<string,int>counting; //记录在查找过程中的次数
    for(i=0;i<=s_len-l_size*word_size;i++)
    {
        counting.clear();
        for(j=0;j<l_size;j++)
        {
            string ss = s.substr(i+j*word_size,word_size); //对每个子串进行遍历
            if(word_count.find(ss)!=word_count.end())
            {
                ++counting[ss];
                if(counting[ss]>word_count[ss]) break;
            }
            else break;
        }
        if(j==l_size)  ans.push_back(i);
    }
    return ans;
}



int main()
{
    string s = "wordgoodstudentgoodword";
    initializer_list<string> lst = {"word","student"};
    vector<string>words(lst);
    vector<int>ans = findSubstring(s,words);
    vector<int>::iterator iter = ans.begin();
    for(;iter!=ans.end();iter++) cout<<*iter;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值