-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🧑💻 improves manacher implementation
- Loading branch information
Showing
2 changed files
with
39 additions
and
50 deletions.
There are no files selected for viewing
43 changes: 18 additions & 25 deletions
43
algorithms/strings/longest-palindrome-substring-(manacher).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,37 @@ | ||
const ll oo = 1e18; | ||
vi manacher(const string &s) { | ||
string t2; | ||
for (auto c : s) t2 += string("#") + c; | ||
t2 = t2 + '#'; | ||
int n = t2.size(); | ||
t2 = "$" + t2 + "^"; | ||
t2.push_back('$'); | ||
for (auto c : s) { | ||
t2.push_back('#'); | ||
t2.push_back(c); | ||
} | ||
t2.push_back('#'); | ||
t2.push_back('^'); | ||
int n = len(t2) - 2; // bc of $ and ^ | ||
vi p(n + 2); | ||
int l = 1, r = 1; | ||
for (int i = 1; i <= n; i++) { | ||
p[i] = max(0, min(r - i, p[l + (r - i)])); | ||
while (t2[i - p[i]] == t2[i + p[i]]) { | ||
p[i]++; | ||
} | ||
if (i + p[i] > r) { | ||
l = i - p[i], r = i + p[i]; | ||
} | ||
while (t2[i - p[i]] == t2[i + p[i]]) p[i]++; | ||
if (i + p[i] > r) l = i - p[i], r = i + p[i]; | ||
p[i]--; | ||
} | ||
return vi(begin(p) + 1, end(p) - 1); | ||
return vi(p.begin() + 1, p.end() - 1); | ||
} | ||
string longest_palindrome(const string &s) { | ||
vi xs = manacher(s); | ||
|
||
string s2; | ||
for (auto c : s) s2 += string("#") + c; | ||
s2 = s2 + '#'; | ||
for (auto c : s) s2.push_back('#'), s2.push_back(c); | ||
s2.push_back('#'); | ||
|
||
// refactor this to use cpp max and iterators arithmetic | ||
int mpos = 0; | ||
for (int i = 0; i < len(xs); i++) { | ||
if (xs[i] > xs[mpos]) { | ||
mpos = i; | ||
} | ||
} | ||
int mpos = max_element(all(xs)) - xs.begin(); | ||
|
||
string ans; | ||
int k = xs[mpos]; | ||
for (int i = mpos - k; i <= mpos + k; i++) { | ||
if (s2[i] != '#') { | ||
ans += s2[i]; | ||
} | ||
} | ||
for (int i = mpos - k; i <= mpos + k; i++) | ||
if (s2[i] != '#') ans.push_back(s2[i]); | ||
|
||
return ans; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters