Minimum Characters required to make a String Palindromic

Given an string A. The only operation allowed is to insert characters in the beginning of the string.

Find how many minimum characters are needed to be inserted to make the string a palindrome string.

Input Format

The only argument given is string A.

Output Format

Return the minimum characters that are needed to be inserted to make the string a palindrome string.

For Example

Input 1:
    A = "ABC"
Output 1:
    2
    Explanation 1:
        Insert 'B' at beginning, string becomes: "BABC".
        Insert 'C' at beginning, string becomes: "CBABC".

Input 2:
    A = "AACECAAAA"
Output 2:
    2
    Explanation 2:
        Insert 'A' at beginning, string becomes: "AAACECAAAA".
        Insert 'A' at beginning, string becomes: "AAAACECAAAA".
public class Solution {
    public boolean checkPalindrome(String A, int start, int end) {
        while (start < end) {
            if (A.charAt(start) != A.charAt(end))
                return false;
            start++;
            end--;
        }
        return true;
    }

    public int solve(String A) {
        int ans = 0;
        for (int i = A.length() - 1; i >= 0; i--) {
            if (A.charAt(0) == A.charAt(i)) {
                if (checkPalindrome(A, 0, i)) {
                    ans = A.length() - (i + 1);
                    break;
                }
            }
        }
        return ans;
    }
}

Last updated