|
| 1 | +/* |
| 2 | + Substring with Concatenation of All Words |
| 3 | + You are given a string, S, and a list of words, L, that are all of the same |
| 4 | + length. Find all starting indices of substring(s) in S that is a |
| 5 | + concatenation of each word in L exactly once and without any intervening |
| 6 | + characters. |
| 7 | +
|
| 8 | + For example, given: |
| 9 | + S: "barfoothefoobarman" |
| 10 | + L: ["foo", "bar"] |
| 11 | +
|
| 12 | + You should return the indices: [0,9]. |
| 13 | + (order does not matter). |
| 14 | +*/ |
| 15 | + |
| 16 | +class Solution { |
| 17 | +public: |
| 18 | + // Increase reference |
| 19 | + int increase(unordered_map<string, int> &hash, string key) { |
| 20 | + if (hash.find(key) == hash.end()) { |
| 21 | + hash.insert(pair<string, int>(key, 1)); |
| 22 | + } else { |
| 23 | + hash[key] = hash[key] + 1; |
| 24 | + } |
| 25 | + return hash[key]; |
| 26 | + } |
| 27 | + |
| 28 | + // Decrease reference |
| 29 | + int decrease(unordered_map<string, int> &hash, string key) { |
| 30 | + if (hash.find(key) == hash.end()) |
| 31 | + return -1; |
| 32 | + if (hash[key] == 1) { |
| 33 | + hash.erase(key); |
| 34 | + return 0; |
| 35 | + } |
| 36 | + hash[key] = hash[key] - 1; |
| 37 | + return hash[key]; |
| 38 | + } |
| 39 | + |
| 40 | + vector<int> findSubstring(string S, vector<string> &L) { |
| 41 | + vector<int> result; |
| 42 | + unordered_map<string, int> toFind, found; |
| 43 | + int n = L.size(), m = L[0].length(); |
| 44 | + |
| 45 | + for (int i=0; i<n; i++) |
| 46 | + increase(toFind, L[i]); |
| 47 | + |
| 48 | + for (int delta=0; delta<m; delta++) { |
| 49 | + if (delta + n * m > S.length()) break; |
| 50 | + found.clear(); |
| 51 | + int l = delta, r = delta; |
| 52 | + while (r < S.length()) { |
| 53 | + string s = S.substr(r, m); |
| 54 | + r += m; |
| 55 | + |
| 56 | + if (toFind.find(s) == toFind.end()) { |
| 57 | + found.clear(); |
| 58 | + l = r; |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + increase(found, s); |
| 63 | + while (found[s] > toFind[s]) { |
| 64 | + string tmp = S.substr(l, m); |
| 65 | + decrease(found, tmp); |
| 66 | + l += m; |
| 67 | + } |
| 68 | + |
| 69 | + if (r - l == n * m) |
| 70 | + result.push_back(l); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return result; |
| 75 | + } |
| 76 | +}; |
0 commit comments