字串中最長迴文字串
阿新 • • 發佈:2019-02-02
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"
class Solution { int sta =0; int max = 0; public String longestPalindrome(String s) { if(s.length()<2) return s; for(int i=0;i<s.length();i++){ check(s,i,i); check(s,i,i+1); } return s.substring(sta,sta+max); } public void check(String s,int left,int right){
// 從字串中間向兩邊擴充套件,搜尋迴文
while(left>=0 && right<s.length() && s.charAt(left) == s.charAt(right)){
left--;
right++;
}
if(max <right - left -1){
sta = left+1;
max = right -left -1;
}
}
}