|
1 | 1 | class Solution { |
2 | | - bool table[256][256]; |
| 2 | + // unordered_map<char, unordered_set<char>>>Map; // 't'-> {'7','8'} |
| 3 | + bool table[128][128]; |
| 4 | + |
3 | 5 | public: |
| 6 | + bool match(char x, char y) |
| 7 | + { |
| 8 | + return (x==y || table[y][x]); |
| 9 | + } |
| 10 | + |
4 | 11 | bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) |
5 | 12 | { |
6 | | - int m = s.size(); |
7 | | - |
8 | 13 | for (auto x: mappings) |
9 | | - { |
10 | 14 | table[x[0]][x[1]] = 1; |
11 | | - } |
12 | 15 |
|
13 | | - return strStr(s, sub)!=-1; |
| 16 | + return strStr(s, sub)!= -1; |
14 | 17 | } |
15 | | - |
16 | | - bool equal(char a, char b) |
17 | | - { |
18 | | - return (a==b || table[b][a]); |
19 | | - } |
20 | | - |
| 18 | + |
21 | 19 | int strStr(string haystack, string needle) |
22 | 20 | { |
23 | | - string s = haystack; |
24 | | - string p = needle; |
25 | | - int n = s.size(); |
26 | | - int m = p.size(); |
27 | | - |
| 21 | + int n = haystack.size(); |
| 22 | + int m = needle.size(); |
28 | 23 | if (m==0) return 0; |
29 | | - if (n==0) return -1; |
| 24 | + if (n==0) return -1; |
| 25 | + |
| 26 | + vector<int> suf = preprocess(needle); |
30 | 27 |
|
31 | 28 | vector<int>dp(n,0); |
32 | | - dp[0] = equal(s[0], p[0]); |
| 29 | + dp[0] = match(haystack[0], needle[0]); |
33 | 30 | if (m==1 && dp[0]==1) |
34 | 31 | return 0; |
35 | | - |
36 | | - vector<int>suffix = preprocess(p); |
37 | | - |
| 32 | + |
38 | 33 | for (int i=1; i<n; i++) |
39 | 34 | { |
40 | | - // compute dp[i] |
41 | 35 | int j = dp[i-1]; |
42 | | - while (j>0 && !equal(s[i], p[j])) |
43 | | - j = suffix[j-1]; |
44 | | - dp[i] = j + equal(s[i], p[j]); |
45 | | - |
46 | | - if (dp[i]==p.size()) |
47 | | - return i - p.size() + 1; |
| 36 | + while (j>0 && !match(haystack[i], needle[j])) |
| 37 | + j = suf[j-1]; |
| 38 | + dp[i] = j + match(haystack[i], needle[j]); |
| 39 | + if (dp[i]==needle.size()) |
| 40 | + return i-needle.size()+1; |
48 | 41 | } |
49 | | - |
50 | 42 | return -1; |
51 | | - |
52 | 43 | } |
53 | 44 |
|
54 | | - vector<int> preprocess(string s) |
| 45 | + bool equal2(char x, char y) |
55 | 46 | { |
56 | | - int n = s.size(); |
57 | | - vector<int>dp(n); |
58 | | - dp[0] = 0; |
| 47 | + if (x==y) return true; |
| 48 | + for (int i=0; i<128; i++) |
| 49 | + if (table[x][i]==table[y][i]) |
| 50 | + return true; |
| 51 | + return false; |
| 52 | + } |
59 | 53 |
|
| 54 | + vector<int> preprocess(string s) |
| 55 | + { |
| 56 | + int n = s.size(); |
| 57 | + vector<int>dp(n,0); |
60 | 58 | for (int i=1; i<n; i++) |
61 | 59 | { |
62 | 60 | int j = dp[i-1]; |
63 | | - while (j>=1 && !equal(s[j],s[i])) |
| 61 | + while (j>=1 && !equal2(s[j],s[i])) |
64 | 62 | { |
65 | 63 | j = dp[j-1]; |
66 | 64 | } |
67 | | - dp[i] = j + equal(s[j], s[i]); |
| 65 | + dp[i] = j + equal2(s[j],s[i]); |
68 | 66 | } |
69 | | - |
70 | 67 | return dp; |
71 | 68 | } |
72 | 69 | }; |
0 commit comments