Java 6 lines solution easy to understand


  • 1
        public String longestPalindrome(String s) {
            int[] best = new int[2];
            for (int i = 0; i < s.length(); i++) {
                extend(s, best, i, i); 
                extend(s, best, i, i + 1); 
            }   
            return s.substring(best[0] + 1, best[1]);
        }   
    
        static void extend(String s, int[] best, int l, int h) { // l and h are exclusive
            while (l >= 0 && h < s.length() && s.charAt(l) == s.charAt(h)) {
                l--;
                h++;
            }   
            if (h - l > best[1] - best[0]) {
                best[0] = l;
                best[1] = h;
            }   
        }
    

Log in to reply
 

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