Leetcode[5] Longest Palindromic Substring

###Task1 Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

###Java ####O(n2) time and O(1) space

public class Solution {
    public String longestPalindrome(String s) {
        int start = 0;
        int end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expand(s, i, i);
            int len2 = expand(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }
    public int expand(String s, int start, int end) {
        int l = start;
        int r = end;
        while (l >= 0 && r <= s.length() - 1 && s.charAt(l) == s.charAt(r)) {
            l--;
            r++;
        }
        return r - l - 1;
    }
}

####O(n2) space

public class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) return "";
        int length = s.length();
        int maxLen = 0;
        String result = "";
        boolean[][] record = new boolean[length][length];

        for (int i = length-1; i >= 0; i--) {
        	for (int j = i; j < length; j++) {
        		if (s.charAt(i) == s.charAt(j) && ((j - i < 2) || (record[i+1][j-1]))) {
        			record[i][j] = true;
        			if (maxLen < (j - i + 1)) {
        				maxLen = j - i + 1;
        				result = s.substring(i, j + 1);
        			}
        		}
        	}
        }
        
        
        return result;
    }
}

###Points