Skip to content

Commit 0e5154c

Browse files
committed
0745 new algo added.
1 parent 96fed65 commit 0e5154c

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

0501-1000/0745-Prefix-and-Suffix-Search/cpp-0745/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ project(cpp_0745)
33

44
set(CMAKE_CXX_STANDARD 14)
55

6-
add_executable(cpp_0745 main.cpp)
6+
add_executable(cpp_0745 main2.cpp)
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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

Comments
 (0)