题目:传送门
题意:给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
暴力:
#include<iostream>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<cstdio>
using namespace std;
class Solution {
public:
int find(vector<string>& words, string str, map<int, bool> p) {
for (int i = 0; i < words.size(); i++) {
if (str == words[i] && p[i] == 0)
return i;
}
return -1;
}
vector<int> findSubstring(string s, vector<string>& words) {
vector<int>ans;
if (words.size() == 0) {
return ans;
}
map<int, bool>p;
int x = words[0].size();
for (int i = 0; i < s.size(); i ++) {
string str;
str.assign(s, i, x);
p.clear();
int flag = find(words, str, p);
//cout << str << "**" << endl;
if (flag == -1)
continue;
p[flag] = 1;
int j = i + x;
while (j < s.size()) {
str.assign(s, j, x);
//cout << str << "**" << endl;
flag = find(words, str, p);
if (flag == -1)
break;
p[flag] = 1;
j += x;
}
int k;
for ( k = 0; k < words.size(); k++) {
if (!p[k])
break;
}
if (k == words.size())
ans.push_back(i);
}
return ans;
}
};
int main() {
string s,word;
vector<string> words;
while (cin >> s) {
words.clear();
while (1) {
cin >> word;
words.push_back(word);
if (cin.get() == '\n')
break;
}
Solution s1;
vector<int>ans;
ans = s1.findSubstring(s, words);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
return 0;
}
暴力不一定出奇迹,时间超限。
哈希map
#include<iostream>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<unordered_map>
#include<cstdio>
using namespace std;
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int>ans;
int len = words[0].length();
if (words.size() == 0||words[0].size()>s.size()) {
return ans;
}
unordered_map<string, int>p;
for (int i = 0; i < words.size(); i++) {
p[words[i]]++;//将word放进哈希表中,并记录个数
}
for (int i = 0; i < s.size(); i++) {
if (s.size() - i < len)
break;
string str = s.substr(i, len);
if (p.find(str) == p.end())
continue;
unordered_map<string, int>p1;
p1 = p;
p1[str]--;
int j ;
for (j = 1; j < words.size(); j++) {
str = s.substr(i + j * len, len);
if (p1.find(str) == p1.end() || p1[str] == 0)
break;
p1[str]--;
}
if (j == words.size())
ans.push_back(i);
}
return ans;
}
};
int main() {
string s,word;
vector<string> words;
while (cin >> s) {
words.clear();
while (1) {
cin >> word;
words.push_back(word);
if (cin.get() == '\n')
break;
}
Solution s1;
vector<int>ans;
ans = s1.findSubstring(s, words);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
return 0;
}
通过减少单词是否是words中这一过程的时间,来降低时间复杂度。