To make the string a palindrome by only appending at the end, we want to find the longest palindromic prefix. The minimum number of appends needed is the number of characters at the start that are not part of this palindrome. We can check for the largest suffix of s that is a palindrome, and the answer is the number of characters before this suffix.
classSolution {
public:bool isPalindrome(const string& s, int l, int r) {
while (l < r) {
if (s[l] != s[r]) return false;
++l; --r;
}
return true;
}
intminAppends(string s) {
int n = s.size();
for (int i =0; i < n; ++i) {
if (isPalindrome(s, i, n-1)) return i;
}
return n-1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
booleanisPalindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r)) returnfalse;
l++; r--;
}
returntrue;
}
publicintminAppends(String s) {
int n = s.length();
for (int i = 0; i < n; ++i) {
if (isPalindrome(s, i, n-1)) return i;
}
return n-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmin_appends(self, s: str) -> int:
defis_palindrome(l: int, r: int) -> bool:
while l < r:
if s[l] != s[r]:
returnFalse l +=1 r -=1returnTrue n = len(s)
for i in range(n):
if is_palindrome(i, n-1):
return i
return n-1