Monday, November 30, 2015

[leetcode]Longest Palindromic Substring

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public String longestPalindrome(String s) {
        boolean isPalindrome[][] = new boolean[s.length()][s.length()];
        int maxStart = 0;
        int maxEnd = 0;
        for (int i = 0; i < s.length(); i++) isPalindrome[i][i] = true;
        for (int i = 1; i < s.length(); i++){
            for (int j = 0; j < s.length()-i; j++){
                isPalindrome[j][j+i] = s.charAt(j) == s.charAt(j+i) && (i <= 1 || isPalindrome[j+1][j+i-1]);
                if (isPalindrome[j][j+i] && i+1 > maxEnd-maxStart){
                    maxStart = j;
                    maxEnd = j+i;
                }
            } 
        }
        return s.substring(maxStart, maxEnd+1);
    }
}

No comments:

Post a Comment