[InterviewBit] Minimum Appends for Palindrome!

Minimum Appends for Palindrome!

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int Solution::solve(string A) {
string ss = "#";
for(auto a : A) {
ss.push_back(a);
ss.push_back('#');
}
vector<int> dp(ss.length());
int l = 0, r = -1, n = ss.size(), mi = ss.length();
for(int i = 0; i < n; i++) {
dp[i] = max(0, min(r - i, r + l - i >= 0 ? dp[r + l - i] : -1));
while(i + dp[i] < n and i - dp[i] >= 0 and ss[i-dp[i]] == ss[i+dp[i]]) dp[i]++;
if(i + dp[i] == n) mi = min(mi, i - dp[i]);
if(r < i + dp[i]) {
r = i + dp[i];
l = i - dp[i];
}
}
int res = 0;
for(int i = 0; i <= mi; i++) res += ss[i] != '#';
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/02/PS/interviewbit/minimum-appends-for-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.