Skip to content

Commit 96b1600

Browse files
authored
Update 2301.Match-Substring-After-Replacement_KMP.cpp
1 parent 41c78b8 commit 96b1600

File tree

1 file changed

+35
-38
lines changed

1 file changed

+35
-38
lines changed
Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,69 @@
11
class Solution {
2-
bool table[256][256];
2+
// unordered_map<char, unordered_set<char>>>Map; // 't'-> {'7','8'}
3+
bool table[128][128];
4+
35
public:
6+
bool match(char x, char y)
7+
{
8+
return (x==y || table[y][x]);
9+
}
10+
411
bool matchReplacement(string s, string sub, vector<vector<char>>& mappings)
512
{
6-
int m = s.size();
7-
813
for (auto x: mappings)
9-
{
1014
table[x[0]][x[1]] = 1;
11-
}
1215

13-
return strStr(s, sub)!=-1;
16+
return strStr(s, sub)!= -1;
1417
}
15-
16-
bool equal(char a, char b)
17-
{
18-
return (a==b || table[b][a]);
19-
}
20-
18+
2119
int strStr(string haystack, string needle)
2220
{
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();
2823
if (m==0) return 0;
29-
if (n==0) return -1;
24+
if (n==0) return -1;
25+
26+
vector<int> suf = preprocess(needle);
3027

3128
vector<int>dp(n,0);
32-
dp[0] = equal(s[0], p[0]);
29+
dp[0] = match(haystack[0], needle[0]);
3330
if (m==1 && dp[0]==1)
3431
return 0;
35-
36-
vector<int>suffix = preprocess(p);
37-
32+
3833
for (int i=1; i<n; i++)
3934
{
40-
// compute dp[i]
4135
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;
4841
}
49-
5042
return -1;
51-
5243
}
5344

54-
vector<int> preprocess(string s)
45+
bool equal2(char x, char y)
5546
{
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+
}
5953

54+
vector<int> preprocess(string s)
55+
{
56+
int n = s.size();
57+
vector<int>dp(n,0);
6058
for (int i=1; i<n; i++)
6159
{
6260
int j = dp[i-1];
63-
while (j>=1 && !equal(s[j],s[i]))
61+
while (j>=1 && !equal2(s[j],s[i]))
6462
{
6563
j = dp[j-1];
6664
}
67-
dp[i] = j + equal(s[j], s[i]);
65+
dp[i] = j + equal2(s[j],s[i]);
6866
}
69-
7067
return dp;
7168
}
7269
};

0 commit comments

Comments
 (0)