# LC 5 Longest Palindromic Substring(M)

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. `public String longestPalindrome(String s)`

**边界条件** 如果字符串长度小于2，直接返回字符串

## 解题思路 DP

以每个字符为中心测试是不是回文，以及最大长度和起点。

```java
private int lo, maxLen;

public String longestPalindrome(String s) {
    int len = s.length();
    if (len < 2)
        return s;

    for (int i = 0; i < len-1; i++) {
         extendPalindrome(s, i, i);  //assume odd length, try to extend Palindrome as possible
         extendPalindrome(s, i, i+1); //assume even length.
    }
    return s.substring(lo, lo + maxLen);
}

private void extendPalindrome(String s, int left, int right) {
    while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
        left--;
        right++;
    }
    if (maxLen < right - left - 1) {
        lo = left + 1;
        maxLen = right - left - 1;
    }
}}
```
