题目链接:https://leetcode.com/problems/longest-palindromic-substring/
解题思路:
1、目的是求最长回文子串,要点在于要设定一个中心。以一个字符为中心向两边扩散和以两个字符为中心向外面扩散。
对于每一个字符,假定它(回文串长度为奇数)或者它和它的右面字符(回文串长度为偶数)是回文串,那么我们只需要向外扩张,直到它不是回文串。
该算法其奥妙在于假定和向外扩张,而不是盲目搜索。
1 class Solution { 2 3 int low=0; 4 int maxLength =0; 5 String res=""; 6 public String longestPalindrome(String s) { 7 if(s.isEmpty()||s.length()<=1) 8 return s; 9 for(int i=0;i<s.length()-1;i++) 10 { 11 Find(s,i,i); 12 Find(s,i,i+1); 13 } 14 15 return res; 16 } 17 18 public void Find(String s,int left,int right) 19 { 20 21 while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)) 22 { 23 if(right-left+1>maxLength) 24 { 25 maxLength=right-left+1; 26 res=s.substring(left,right+1);//java中的substring是左闭右开的 27 } 28 left--; 29 right++; 30 } 31 32 } 33 34 }