LeetCode – Shortest Palindrome (Java)

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example, given “aacecaaa”, return “aaacecaaa”; given “abcd”, return “dcbabcd”.

Java Solution 1

public String shortestPalindrome(String s) {
    int i=0; 
    int j=s.length()-1;
 
    while(j>=0){
        if(s.charAt(i)==s.charAt(j)){
            i++;
        }
        j--;
    }
 
    if(i==s.length())
        return s;
 
    String suffix = s.substring(i);
    String prefix = new StringBuilder(suffix).reverse().toString();
    String mid = shortestPalindrome(s.substring(0, i));
    return prefix+mid+suffix;
}

Java Solution 2

We can solve this problem by using one of the methods which is used to solve the longest palindrome substring problem.

Specifically, we can start from the center and scan two sides. If read the left boundary, then the shortest palindrome is identified.

public String shortestPalindrome(String s) {
	if (s == null || s.length() <= 1)
		return s;
 
	String result = null;
 
	int len = s.length();
	int mid = len / 2;	
 
	for (int i = mid; i >= 1; i--) {
		if (s.charAt(i) == s.charAt(i - 1)) {
			if ((result = scanFromCenter(s, i - 1, i)) != null)
				return result;
		} else {
			if ((result = scanFromCenter(s, i - 1, i - 1)) != null)
				return result;
		}
	}
 
	return result;
}
 
private String scanFromCenter(String s, int l, int r) {
	int i = 1;
 
	//scan from center to both sides
	for (; l - i >= 0; i++) {
		if (s.charAt(l - i) != s.charAt(r + i))
			break;
	}
 
	//if not end at the beginning of s, return null 
	if (l - i >= 0)
		return null;
 
	StringBuilder sb = new StringBuilder(s.substring(r + i));
	sb.reverse();
 
	return sb.append(s).toString();
}

12 thoughts on “LeetCode – Shortest Palindrome (Java)”

  1. Based on the problem statement, you are allowed to add characters only in front of the original string. Therefore, under these conditions, the shortest palindrome is guaranteed to have a suffix of “abb”.

  2. This solution could work?

    public String shortestPalindrome(String input){
    StringBuilder preff = new StringBuilder();
    StringBuilder suff = new StringBuilder();

    Stack stack = new Stack();

    stack.addAll(Arrays.asList( input.split(“”)));
    String lastElement;
    while(!stack.isEmpty()){
    if( stack.size() == 1 ){
    preff.append(stack.firstElement());
    stack.clear();
    continue;
    }

    lastElement = stack.pop();

    preff.append(lastElement);
    suff.insert(0, lastElement);

    if(lastElement.equals(stack.firstElement())){
    stack.remove(0);
    }
    }

    return preff.toString() + suff.toString();
    };

  3. In Java Solution 1, String mid = shortestPalindrome(s.substring(0, i)); should be String mid = s.substring(0, i);


  4. public static String shortestPalindrome(String s) {
    StringBuilder result = new StringBuilder();
    int i = s.length() - 1;
    int j = 0;

    while (i > j) {
    if (s.charAt(i) == s.charAt(j)) {
    i--;
    j++;
    }
    else {
    result.append(s.charAt(i));
    i--;
    }
    }
    return result.append(s).toString();
    }

  5. Following change can pass the online verification.

    public class Solution {
    public String shortestPalindrome(String s) {
    if (s == null || s.length() =0; i--) {
    if (s.charAt(i) == s.charAt(i+1)) {
    if ((result = scan(s, i, i+1)) != null) {
    return result;
    }
    }
    if ((result = scan(s, i, i)) != null) {
    return result;
    }
    }

    return result;
    }

    String scan (String s, int l, int r) {
    int i = 1;
    for (; l-i>=0&&r+i=0) return null;

    StringBuilder sb = new StringBuilder(s.substring(r+i));
    sb.reverse();
    return sb.append(s).toString();
    }
    }

  6. Above program is wrong for some of the testcases such as aaabcbaa.check this program it works for all the testcases….

    import java.util.*;
    class makepalindrome
    {
    public static void main(String args[])
    {
    Scanner sc = new Scanner(System.in);
    System.out.println(“Enter a String to process”);
    String s = sc.nextLine();
    String s1 = makepalin1(s,s.length()-1,0);
    String s2 = makepalin2(s,s.length()-1,0);
    //The String with the shortest length is printed
    System.out.println(s1.length()>s2.length()?s2:s1);
    sc.close();
    }
    public static String makepalin1(String s, int count, int pos)
    {
    //System.out.println(s + ” count: ” + count + “pos: ” + pos);

    if(count <= 0)
    return s;
    else

    if(s.charAt(count) != s.charAt(pos))
    return s.charAt(count) + makepalin1(s.substring(pos, count),count-1,pos) + s.charAt(count)

    else
    return s.charAt(pos) + makepalin1(s.substring(pos+1, count),count-2,pos) +s.charAt(pos);
    }

    public static String makepalin2(String s, int count, int pos)
    {
    //System.out.println(s + " count: " + count + "pos: " + pos);

    if(count <= 0)
    return s;
    else
    if(s.charAt(count) != s.charAt(pos))
    return s.charAt(pos) + makepalin2(s.substring(pos+1, count+1),count-1,pos) + s.charAt(pos);

    else
    return s.charAt(pos) + makepalin2(s.substring(pos+1, count),count-2,pos) +s.charAt(pos);
    }
    }

  7. this solution is not correct..
    Submission Result: Wrong AnswerMore Details
    Input:”aba”
    Output:”ababa”
    Expected:”aba”

Leave a Comment