Simple Recursive solutions 4ms


  • 0
    public class Solution {
        public String shortestPalindrome(String s) {
            int j=s.length()-1;;
            int i=0;
            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 StringBuffer(suffix).reverse().toString();
            String mid = shortestPalindrome(s.substring(0,i));
            return prefix+mid+suffix;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.