# LeetCode 5：Longest Palindromic Substring

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.
```

Example:

```Input: "cbbd"

Output: "bb"```

Java源码如下

`package com.maoxiaomeng;/** * @author lihui * @date 2018/3/25 11:29 */public class Solution {        private int start;    private int maxLen;        public void getPosAndLength(String s, int left, int right) {        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {            left--;            right++;        }                //h e a b c d c b a f a        //  l l l l   r r r r        //h e a b c d d c b a f a        //  l l l l l r r r r r                int subLen = right - left - 1;        if (subLen > maxLen) {            maxLen = subLen;            start = left + 1;        }    }        public String longestPalindrome(String s) {        int len = s.length();        if (len <= 1) {            return s;        }                for (int i = 0; i < len - 1; i++) {            getPosAndLength(s, i, i);            getPosAndLength(s, i, i + 1);        }        return s.substring(start, start + maxLen);    }}`

getPosAndLength方法后面两个参数分两种情况，如果s是单数字符，那么两个指针初始都同一个位置；如果双数，就相邻两个两边扩张；while里的条件顺序不能颠倒了，如果先判断两个字符相等，就会index越界，因为存在相同字符才有left- -，那么如果到了边界，最终left=-1就越界了，所以得先判断left和right，最终比较maxLen即可获取最大长度，同时子串起始位置要+1，因为上面–了