Java Short and Clean (13 line two pointer solution)


  • -6
    N
    public String longestPalindrome(String s) {
        String ret = "";
        for (int i = 0; i < s.length(); i++) {
            int p = i, q = i;
            while (q < s.length() - 1 && s.charAt(q + 1) == s.charAt(q)) {
                q++;
            }
            while (p >= 0 && q <= s.length() - 1 && s.charAt(p) == s.charAt(q)) {
                if (q - p + 1 > ret.length()) ret = s.substring(p, q + 1);
                p--;
                q++;
            }
        }
        return ret;
    }

  • 0
    J

    I think p--; q++; should be outside the if sentence and within the while loop.


Log in to reply
 

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