[InterviewBit] Minimum Characters required to make a String Palindromic

Minimum Characters required to make a String Palindromic

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int Solution::solve(string A) {
string s = "#";
for(auto ch : A) {
s.push_back(ch);
s.push_back('#');
}
vector<int> dp(s.size());
int ma = 0;
for(int i = 0, l = 0, r = -1; i < s.size(); i++) {
dp[i] = max(0, min(r - i, r + l - i >= 0 ? dp[r + l - i] : -1));
while(i + dp[i] < s.size() and i - dp[i] >= 0 and s[i + dp[i]] == s[i - dp[i]]) dp[i]++;
if(r < i + dp[i]) {
r = i + dp[i];
l = i - dp[i];
}
if(i - dp[i] == -1) ma = i + dp[i];
}
int res = 0;
for(int i = ma; i < s.size(); i++) res += s[i] != '#';
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/17/PS/interviewbit/minimum-characters-required-to-make-a-string-palindromic/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.