005 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"
详见:https://leetcode.com/problems/longest-palindromic-substring/description/
Java实现:
class Solution { public String longestPalindrome(String s) { int size=s.length(); if(size==1||s.isEmpty()){ return s; } int len=0; int start=0; int end=0; for(int i=0;i<size;++i){ int len1=helper(s,i,i); int len2=helper(s,i,i+1); len=Math.max(len1,len2); if(len>(end-start)){ start=i-(len-1)/2; end=i+(len/2); } } return s.substring(start,end+1); } private int helper(String s,int start,int end){ while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){ --start; ++end; } return (end-start-1); } }