问题描述
给定一个字符串 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;
}
输入说明
首先收入字符串s,
然后输入words中单词的数目n,
最后输入n个字符串,表示words中的单词
输出说明
按照索引由小到大顺序输出,或者输出-1.
输入范例
barfoothefoobarman
2
foo bar
输出范例
0 9
实现思路
思路与判断是否为字母异位词一样,只不过本题是判断单词是否异位。(但本代码对那个巨长的a字符串会运行超时)
实现代码
#include <iostream>
#include<sstream>
#include <vector>
#include<math.h>
#include<unordered_map>
using namespace std;
class Solution {
public:
bool isAnagram(vector<string>&a,vector<string>&b){
unordered_map<string,int>mp;
for(int i = 0;i<a.size();i++){
mp[a[i]]++;
}
for(int i = 0;i<b.size();i++){
mp[b[i]]--;
}
for(std::unordered_map<string,int>::iterator it = mp.begin();it!=mp.end();++it){
if(it->second!=0) return false;
}
return true;
}
vector<int> findSubstring(string s, vector<string>& words) {
vector<string> str;
vector<int>res;
/*for(int i = 0;i<words.size();i++){
str += words[i];
}*/
int n = words.size()*words[0].size();//words所有单词的长度
for(int i = 0;i<s.size()-n+1;i++){
string tem = "";
for(int j = i;j<i+n;j++){
tem += s[j];
if(tem.size()==words[0].size()){
str.push_back(tem);
tem = "";
}
}
if(isAnagram(words,str)) res.push_back(i);
str.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=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;
}