最长回文子串

#include <iostream>    
#include <vector>
#include <string>
#include <algorithm>

using namespace std;
//最长回文子串
//有字母s,用c[i,j]=1表示子串s[i,j]为回文子串,那么有递推式
//           c[i,j]=c[i+1,j-1]  if(s[i]==s[j])
//           c[i,j]=0           if(s[i]!=s[j])
int longest(string str)
{
	int len = str.length();
	int c[100][100];
	int i, j;
	int longest = 1;

	if (str.length() == 0)
		return 0;
	if (str.length() == 1)
		return 1;

	for (i = 0; i < len; i++)
	{
		c[i][i] = 1;
		if (str[i] == str[i + 1])
			c[i][i + 1] = 1;
	}

	for (i = 0; i < len; i++)
	{
		for (j = i + 2; j <= len; j++)
		{
			if (str[i] == str[j])
			{
				c[i][j] = c[i + 1][j - 1];
				if (c[i][j])
				{
					int n = j - i + 1;
					if (longest < n)
						longest = n;
				}
			}
			else
				c[i][j] = 0;
		}
	}
	return longest;
}
void main()
{
	string str;
	cin >> str;
	cout << longest(str);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值