力扣练习——70 串联所有单词的子串

1.问题描述

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

输入:

  s = "barfoothefoobarman",

  words = ["foo","bar"]

输出:0 9

解释:

从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。输出时,按照索引由小到大顺序输出。

 

示例 2:

输入:

  s = "wordgoodgoodgoodbestword",

  words = ["word","good","best","word"]

输出:-1

s中的子串无法由words串联得到,所以输出-1

 

可使用以下main函数:

int main()

{

    string s,str;

    vector<string> words;

    int n;

    cin>>s;

    cin>>n;

    for(int i=0; i<n; i++)

    {

        cin>>str;

        words.push_back(str);

    }

    vector<int> res=Solution().findSubstring(s, words);

    if (res.size()> 0)

        for(int i=0; i<res.size(); i++)

        {

            if (i> 0)

                cout<<" ";

            cout<<res[i];

        }

    else

        cout<<-1;

 

    return 0;

}

2.输入说明

首先收入字符串s,

然后输入words中单词的数目n,

最后输入n个字符串,表示words中的单词

3.输出说明

按照索引由小到大顺序输出,或者输出-1.

4.范例

输入

barfoothefoobarman
2
foo bar

输出

0 9

5.代码

#include<iostream>
#include<map>
#include<string>
#include<unordered_map>
#include<algorithm>
#include<string.h>
#include<sstream>
#include <vector>

using namespace std;

vector<int> findSubstring(string s, vector<string> words)
{
    int word_len = words[0].size();//每个单词长度
    int s_len = s.size();
    int word_cnt = words.size();//总共有m个单词
    if (word_len == 0 || s_len == 0 || word_cnt == 0) return vector<int>{};

    unordered_map<string, int>word;//记录每个单词出现的次数
    for (auto it : words)
        word[it]++;

    vector<int> res;//结果
    
    unordered_map<string, int>tmp;
    
    int j;
    for (int i = 0; (i+ word_len*word_cnt ) <= s.size(); i++)//这里等号必须要加,否则会出错
    {
        for ( j = i; j < (i+word_len*word_cnt); j+=word_len)
        {
            string tmp_s = s.substr(j, word_len);//易错点1:substr(index,len) 第一个参数为下标,第二个为截取的长度
            //判断截取的子串是否存在于word中,且次数是否相等
            if (word[tmp_s] == 0)//不存在该单词,直接退出
                break;
            else
            {
                tmp[tmp_s]++;//哈希表更新
                if (word[tmp_s] < tmp[tmp_s])//重复次数过多,也要退出
                    break;
            }
        }
        
        if (j == (i + word_len * word_cnt))//遍历到末尾了
            res.push_back(i);    
        tmp.clear();//每次遍历结束都要清空临时哈希表
    }
    return res;
}
int main()

{

    string s, str;

    vector<string> words;

    int n;

    cin >> s;

    cin >> n;

    for (int i = 0; i < n; i++)

    {

        cin >> str;

        words.push_back(str);

    }

    vector<int> res = findSubstring(s, words);

    if (res.size() > 0)

        for (int i = 0; i < res.size(); i++)

        {

            if (i > 0)

                cout << " ";

            cout << res[i];

        }

    else

        cout << -1;



    return 0;

}

 

posted @ 2022-08-15 13:28  努力奋斗的小企鹅  阅读(63)  评论(0)    收藏  举报