A simple java solution


  • 2
    A
    public class Solution {
        public int start = 0;
        public int length = 1;
        public String longestPalindrome(String s) {
            int len = s.length();
            if(len == 0 || len ==1 )
                return s;
            if(len==2){
                if(s.charAt(0)==s.charAt(1)) return s;
                else return s.charAt(0)+"";
            }
            for(int i=0;i<len;i++){
                getMaxPalindrome(s, i, i);
                getMaxPalindrome(s, i, i+1);
            }
            return s.substring(start,start+length);
        }
        
        
        public void getMaxPalindrome(String s, int i, int j){
           while(i>=0 && j<s.length()&&s.charAt(i)==s.charAt(j)){
               i--;j++;
           }
           if(j-i>length){
               length=j-i-1;
               start = ++i;
           }
        }
    }

Log in to reply
 

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