题解 | #密码截取#
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
遍历字符串。以当前字符为中心,向两侧做双指针遍历,以查找当前字符为中心情况下的回文子序列。
此时有两种情况,一种是aba, 一种是abba,即中心为当前字符,或者当前字符和下一个字符之间的空隙。
写两个方法,分别求上面两种情况的回文序列长度,并作比较保留最大的。
将当前轮次最长回文序列与全局参数对比,保留最大的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectSample
{
//HJ32
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
int max = 1;
// i as center
for (int i = 0; i < input.Length; i++)
{
int this_max = Math.Max(centerINextMax(i, input, max), centerIMax(i, input, max));
max = Math.Max(this_max, max);
}
Console.WriteLine(max);
}
static int centerIMax(int i, string input, int max)
{
int count = 1;
var curr_i_c = input[i];
for (int j = i + 1, k = i - 1; j < input.Length && k >= 0; j++, k--)
{
if (input[k].Equals(input[j]))
{
count += 2;
}
else
{
max = Math.Max(max, count);
count = 0;
break;
}
}
max = Math.Max(max, count);
return max;
}
static int centerINextMax(int i, string input, int max)
{
int count = 0;
var curr_i_c = input[i];
for (int j = i + 1, k = i; j < input.Length && k >= 0; j++, k--)
{
if (input[k].Equals(input[j]))
{
count += 2;
}
else
{
max = Math.Max(max, count);
count = 0;
break;
}
}
max = Math.Max(max, count);
return max;
}
}
}
查看19道真题和解析