Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            String tmp = lookup(i, i, s);
            res = tmp.length() > res.length() ? tmp : res;
            // check the pattern like abba which there are 2 same chars at the middle
            tmp = lookup(i, i + 1, s);
            res = tmp.length() > res.length() ? tmp : res;
        }
        return res;
    }

    private String lookup(int left, int right, String s) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        // as substring method include start index but exclude end index, left need to be plused 1.
        return s.substring(left + 1, right);
    }
}