题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

// HJ85-2 最长回文子串.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include<iostream>
#include<bits/stdc++.h>

using namespace std;

int check(string& s, int x)
{
	int j = x,k=x+1,ans=0, len = s.size();
	while (j >= 0 && (k <=len - 1))
	{
		if (s[j] == s[k])
		{
			ans+=2;
			j--;
			k++;
		}
		else if (s[j] != s[k])
		{
			break;
		}
	}
	return ans;
}

int check1(string& s, int x)
{
	int j = x-1, k = x + 1, ans = 1,len=s.size();
	while(j>=0&&(k<=len-1))
	{
		if (s[j] == s[k])
		{
			ans+=2;
			j--;
			k++;
		}
		else if (s[j] != s[k])
		{
			break;
		}
			
	}
	return ans;
}
int main()
{
	string s;
	while (cin >> s)
	{
		int res = 0;
		for (int i = 0; i < s.size(); i++)
		{
			int a=check(s, i);
			int b=check1(s, i);
			int tmp = max(a, b);
			res = max(res,tmp);
		}
		cout << res << endl;
	}
	return 0;
}

全部评论

相关推荐

牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务