力扣 题目30-- 串联所有单词的子串

题目


题解


暴力解法(思路来自评论区的老哥)

 

这里应该将题目中给的vector改为unordered_map容器然后去查找才能比较快捷

代码


 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 #include<unordered_map>
 5 using namespace std;
 6 class Solution {
 7 public:
 8     vector<int> findSubstring(string s, vector<string>& words) {
 9         vector<int> result;
10         int len = words[0].size();
11         int wordsize = len * words.size();
12         int superposition = 0;
13         while (wordsize <= s.size()) {
14             unordered_map<string, int> mp, tmp;
15             for (auto str : words) {
16                 ++mp[str];
17             }
18         for (int i = 0; i < wordsize;) {
19             string &&str = s.substr(i, len);
20             if (mp.find(str) == mp.end()) break;
21             ++tmp[str];
22             i = i + len;
23         }
24         if (tmp == mp) result.push_back(superposition);
25         tmp.clear();
26         s=s.substr(1, s.size() - 1);
27         superposition = superposition + 1;
28         }
29         return result;
30     }
31 };
32 int main() {
33     string s = "wordgoodgoodgoodbestword";
34     vector<string> words = { "word","good","best","good" };
35     Solution sol;
36     vector<int> result=sol.findSubstring(s,words);
37     for (int i = 0; i < result.size(); i++) {
38         cout << result[i] << endl;
39     }
40 }
View Code

 

 

 

posted @ 2022-04-20 14:27  无聊的阿库娅  阅读(21)  评论(0编辑  收藏  举报