Want to share my easy to understand java solution.


  • 0
    Z
    class Solution {
        public static String longestPalindrome(String s) {
            int start = Integer.MAX_VALUE, end = Integer.MIN_VALUE, max = 0;
            for (int i = 0; i < s.length(); i++) {
                int len1 = (helper(s, i, i) - 1) * 2 + 1;
                int len2 = helper(s, i, i + 1) * 2;
                int len = Math.max(len1, len2);
                
                if (len > max) {
                    if (len == len1) {
                        start = i - (len - 1) / 2;
                        end = i + (len - 1) / 2;
                    } else if (len == len2) {
                        start = i - len / 2 + 1;
                        end = i + len / 2;
                    }
                    max = len;
                }
                
            }
            return end >= start ? s.substring(start, end + 1) : "";
        }
    
        private static int helper(String s, int i, int j) {
            int count = 0;
            while (i >= 0 && j < s.length()) {
                if (s.charAt(i--) != s.charAt(j++)) {
                    return count;
                }
                count++;
            }
            return count;
        }
    }
    

Log in to reply
 

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