|
| 1 | +/// Source : https://leetcode.com/problems/substring-with-concatenation-of-all-words/ |
| 2 | +/// Author : liuyubobobo |
| 3 | +/// Time : 2022-06-22 |
| 4 | + |
| 5 | +#include <iostream> |
| 6 | +#include <vector> |
| 7 | +#include <map> |
| 8 | + |
| 9 | +using namespace std; |
| 10 | + |
| 11 | + |
| 12 | +/// Sliding Window |
| 13 | +/// Time Complexity: O(word_len * |s|) |
| 14 | +/// Space Complexity: O(|s|) |
| 15 | +class Solution { |
| 16 | +public: |
| 17 | + vector<int> findSubstring(string s, vector<string>& words) { |
| 18 | + |
| 19 | + int word_len = words[0].size(); |
| 20 | + |
| 21 | + map<string, int> words_f; |
| 22 | + for(int i = 0; i < words.size(); i ++) words_f[words[i]] ++; |
| 23 | + |
| 24 | + vector<int> res; |
| 25 | + for(int start = 0; start < word_len; start ++){ |
| 26 | + |
| 27 | + vector<string> data; |
| 28 | + for(int i = start; i < s.size(); i += word_len) |
| 29 | + data.push_back(s.substr(i, word_len)); |
| 30 | + |
| 31 | + int ok_cnt = 0, l = 0, r = -1; |
| 32 | + map<string, int> cur_f; |
| 33 | + while(l < (int)data.size()){ |
| 34 | + if(r + 1 < (int)data.size() && words_f.count(data[r + 1]) && cur_f[data[r + 1]] + 1 <= words_f[data[r + 1]]){ |
| 35 | + cur_f[data[r + 1]] ++; |
| 36 | + |
| 37 | + if(cur_f[data[r + 1]] == words_f[data[r + 1]]){ |
| 38 | + ok_cnt ++; |
| 39 | + if(ok_cnt == words_f.size()) |
| 40 | + res.push_back(start + l * word_len); |
| 41 | + } |
| 42 | + |
| 43 | + r ++; |
| 44 | + } |
| 45 | + else{ |
| 46 | + |
| 47 | + if(words_f.count(data[l])){ |
| 48 | + cur_f[data[l]] --; |
| 49 | + if(cur_f[data[l]] + 1 == words_f[data[l]]) ok_cnt --; |
| 50 | + } |
| 51 | + l ++; |
| 52 | + r = max(r, l - 1); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return res; |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | + |
| 62 | +void print_vec(const vector<int>& v){ |
| 63 | + for(int e: v) cout << e << ' '; cout << '\n'; |
| 64 | +} |
| 65 | + |
| 66 | +int main() { |
| 67 | + |
| 68 | + vector<string> words1 = {"foo", "bar"}; |
| 69 | + print_vec(Solution().findSubstring("barfoothefoobarman", words1)); |
| 70 | + // 0 9 |
| 71 | + |
| 72 | + vector<string> words2 = {"word","good","best","word"}; |
| 73 | + print_vec(Solution().findSubstring("wordgoodgoodgoodbestword", words2)); |
| 74 | + // empty |
| 75 | + |
| 76 | + vector<string> words3 = {"bar","foo","the"}; |
| 77 | + print_vec(Solution().findSubstring("barfoofoobarthefoobarman", words3)); |
| 78 | + // 6 9 12 |
| 79 | + |
| 80 | + return 0; |
| 81 | +} |
0 commit comments