[AlgoExpert] Underscorify Substring

Underscorify Substring

  • Time : O(n + m)
  • Space : O(n + m)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using namespace std;

vector<int> PI(string& s) {
int n = s.length();
vector<int> pi(n);
for(int i = 1, j = 0; i < n; i++) {
while(j > 0 and s[i] != s[j]) j = pi[j - 1];
if(s[i] == s[j])
pi[i] = ++j;
}
return pi;
}

vector<int> kmp(string& s, string& p) {
int n = s.length(), m = p.length();
auto pi = PI(p);
vector<int> res;
for(int i = 0, j = 0; i < n; i++) {
while(j > 0 and s[i] != p[j]) j = pi[j - 1];
if(s[i] == p[j]) {
if(++j == m) {
res.push_back(i - j + 1);
j = pi[j - 1];
}
}
}
return res;
}

string underscorifySubstring(string s, string p) {
auto match = kmp(s, p);
int plen = p.length();
vector<int> in{INT_MIN}, out{INT_MIN};
for(int i = 0; i < match.size(); i++) {
if(in.back() + plen < match[i] and out.back() + 1 < match[i]) {
in.push_back(match[i]);
out.push_back(match[i] + plen - 1);
} else {
out.back() = match[i] + plen - 1;
}
}
string res = "";
for(int i = 0, j = 1, k = 1; i < s.length(); i++) {
if(j < in.size() and in[j] == i) {
res.push_back('_');
j++;
}
res.push_back(s[i]);
if(k < out.size() and out[k] == i) {
res.push_back('_');
k++;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/underscorify-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.