题解 | #最长回文子串-中心扩散法#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
中心扩散法。
为了避免对“BAAB“这种形式的字符串做特殊处理,可以先对输入字符串做下预处理,即:每个字符前后加上'#',这样直接遍历每个字符,以当前字符为中心进行两端扩散,若两边字符不相等或者索引越界,直接计算出含”#“的回文子串的长度,减一(去掉多的哪一个#)除2即可得到回文子串长度
using System;
class Solution
{
public int getLongestPalindrome(string A, int n)
{
// write code here
int templen = n * 2 + 1;
char[] chs = new char[templen];
int k = 0;
for(int i = 0; i < n; i++){
chs[k++] = '#';
chs[k++] = A[i];
}
chs[templen - 1] = '#';
int maxP = 0;
for(int i = 0; i < templen; i++){
int l = i-1, r = i+1;
while(l >= 0 && r <= templen - 1 && chs[l] == chs[r]){
l--;
r++;
}
int count = (r - l - 1 - 1) / 2;
maxP = Math.Max(maxP, count);
}
return maxP;
}
}
京东公司氛围 301人发布