Java O(n^2) Concise Solution


  • 0
    public class Solution {
        public String shortestPalindrome(String s) {
            int n = s.length();
            if(n == 0) return s;
            if(isPalindrome(s))return s;
            String add = s;
            for(int i = n - 1; i >= 1; i--){
                String s1 = s.substring(0,i);
                if(isPalindrome(s1)){
                    add = new StringBuilder(s.substring(i)).reverse().toString();
                    break;
                }
            }
            return add+s;
        }
        public boolean isPalindrome(String s){
            int n = s.length();
            for(int i = 0; i < n/2; i++){
                if(s.charAt(i) != s.charAt(n-i-1))return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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