|
| 1 | +/// Source : https://leetcode.com/problems/prefix-and-suffix-search/ |
| 2 | +/// Author : liuyubobobo |
| 3 | +/// Time : 2022-07-14 |
| 4 | + |
| 5 | +#include <iostream> |
| 6 | +#include <vector> |
| 7 | +#include <algorithm> |
| 8 | +#include <map> |
| 9 | + |
| 10 | +using namespace std; |
| 11 | + |
| 12 | + |
| 13 | +/// Using Hash + Map |
| 14 | +/// Time Complexity: init: O(|words| * len^2) |
| 15 | +/// query: O(|prefix| + |suffix|) |
| 16 | +/// Space Complexity: O(|words| * len^2) |
| 17 | +class WordFilter { |
| 18 | + |
| 19 | +private: |
| 20 | + map<pair<long long, long long>, int> table; |
| 21 | + |
| 22 | +public: |
| 23 | + WordFilter(vector<string> words) { |
| 24 | + |
| 25 | + for(int i = 0 ; i < words.size() ; i ++) |
| 26 | + insert(words[i], i); |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + int f(string prefix, string suffix) { |
| 31 | + |
| 32 | + long long pre_hash = 0; |
| 33 | + for(int i = 0; i < prefix.size(); i ++) |
| 34 | + pre_hash = pre_hash * 27 + (prefix[i] - 'a' + 1); |
| 35 | + |
| 36 | + long long suf_hash = 0; |
| 37 | + for(int i = suffix.size() - 1; i >= 0; i --) |
| 38 | + suf_hash = suf_hash * 27 + (suffix[i] - 'a' + 1); |
| 39 | + |
| 40 | + auto iter = table.find({pre_hash, suf_hash}); |
| 41 | + return iter == table.end() ? -1 : iter->second; |
| 42 | + } |
| 43 | + |
| 44 | +private: |
| 45 | + void insert(const string& s, int index){ |
| 46 | + |
| 47 | + long long pre_hash = 0; |
| 48 | + for(int i = 0; i < s.size(); i ++){ |
| 49 | + pre_hash = pre_hash * 27 + (s[i] - 'a' + 1); |
| 50 | + |
| 51 | + long long suf_hash = 0; |
| 52 | + for(int i = s.size() - 1; i >= 0; i --){ |
| 53 | + suf_hash = suf_hash * 27 + (s[i] - 'a' + 1); |
| 54 | + table[{pre_hash, suf_hash}] = index; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +}; |
| 59 | + |
| 60 | + |
| 61 | +int main() { |
| 62 | + |
| 63 | + return 0; |
| 64 | +} |
0 commit comments