给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
示例 1:
1 2 3
|
输入: "babad" 输出: "bab" 注意: "aba"也是一个有效答案。
|
示例 2:
解法一:
从一个点向两边扩展,当两边的数值一样,那就是回文子串。
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 26 27 28 29 30 31 32 33 34
|
class { public String longestPalindrome(String s) { if(s==null){ return null; } int len=s.length(); int sta=0; int max=0; for (int i=0;i<s.length();i++){ int low=i-1,height=i+1; while(low>=0&&height<len&&s.charAt(low)==s.charAt(height)){ low--; height++; } if (height-low-1>max){ max=height-low-1; sta=low+1; } low=i-1; height=i; while (low>=0&&height<len&&s.charAt(low)==s.charAt(height)){ low--; height++; } if (height-low-1>max){ max=height-low-1; sta=low+1; } } return s.substring(sta,sta+max); } }
|
解法二:
近期评论