中心扩散法。注意中心值奇数偶数个的问题
/**
* NC17 最长回文子串 获取最长回文子串;回文子串:正反读相同;
* @param str
* @param n
* @return
*/
public int getLongestPalindrome(String str, int n) {
// write code here
char[] chars = str.toCharArray();
int res=0;
for (int i = 1; i < n; i++) {
res=Math.max(res,expandAroundCenter(chars,i,i));
res=Math.max(res,expandAroundCenter(chars,i,i+1));
}
return res;
}private int expandAroundCenter(char[] s,int left,int right){
int l=left,r=right;
while (l>=0&&r<s.length&&s[l]==s[r]){
l--;
r++;
}
return r-l-1;
}
京公网安备 11010502036488号