714300. Make Palindrome
Here is the detailed blog post for the "Make Palindrome" problem:
Make Palindrome
Summary
Given a string, make it palindrome by adding characters at the beginning and end. The goal is to find the minimum number of operations (addition or deletion) to make the string a palindrome.
This problem involves string manipulation and palindrome concepts.
Detailed Explanation
To solve this problem, we can start by finding the middle of the string. Then, we compare the characters from both sides of the middle. If they are not equal, we add the missing character at the beginning or end to make it a palindrome.
Here is a step-by-step breakdown of the solution:
- Find the middle of the string.
- Compare the characters from both sides of the middle.
- If they are not equal, add the missing character at the beginning or end.
- Repeat steps 2 and 3 until the entire string is a palindrome.
Here's an example: if we have the string "abc", we would add "a" at the beginning to make it "aba".
Time complexity: O(n), where n is the length of the input string.
Space complexity: O(1), as we only use a constant amount of space.
Optimized Solutions
Java
public class MakePalindrome {
public static String makePalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
if (left == 0) {
return s.substring(0, right + 1) + s.charAt(right);
} else if (right == s.length() - 1) {
return s.charAt(left) + s.substring(left, s.length());
}
return s.substring(0, left) + s.charAt(left) + s.substring(left, right + 1) + s.charAt(right);
}
left++;
right--;
}
return s;
}
}