My easy to under stand java solution


  • 0
    J
    public class Solution {
        public String longestPalindrome(String s) {
            if(s == null || s.length() == 0) return "";
            int l = 0, r = 0, len = 0;
            for(int i = 0; i < s.length() - 1; i++){
                int len1 = expand(s, i, i);
                if(len1 > len){
                    l = i;
                    r = i;
                    len = len1;
                }
                int len2 = expand(s, i, i + 1);
                if(len2 > len){
                    l = i;
                    r = i + 1;
                    len = len2;
                }
            }
            if(len == 0) return s;
            return len%2 == 0?s.substring(l - (len-1)/2, r + (len-1)/2 + 1):s.substring(l - len/2, r + len/2 + 1);
        }
        private int expand(String s, int left, int right){
            int len = 0;
            if(left == right){
                len = -1;
            }
            while(left >= 0 && right < s.length()){
                if(s.charAt(left) != s.charAt(right)){
                    break;
                }
                left--;
                right++;
                len+=2;
            }
            return len;
        }
    }
    

Log in to reply
 

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