Leetcode-最长回文子串

69.最长回文子串

题目内容:

Leetcode-最长回文子串_第1张图片

代码及思路:

1)首先理解什么是回文子串:从左到右和从右到左是一样的。

2)

Leetcode-最长回文子串_第2张图片

#include
#include
#include
using namespace std;
class Solution {
public:
	string longestPalindrome(string s)
	{
		if (s.empty())
			return "";
		if (s.size() == 0 || s.size() == 1)
			return s;
		int len = s.size();
		int start = 0;
		int max = 1;
		vector> dp(len, vector(len)); //二维动态数组
		for (int i = 0; i < len; i++)
		{
			dp[i][i] = 1; //单个字符是回文串
			if (i < len - 1 && s[i] == s[i + 1])
			{
				dp[i][i + 1] = 1; //相邻两个字符如果相等,则为回文子串
				max = 2;
				start = i;
			}
		}
		for (int l = 3; l <= len;l++) //其他可能,也就是长度大于3的子串,检索子串的长度,从长度为3的子串开始
		{
			for (int i = 0; i + l - 1 < len; i++)
			{
				int j = l+i - 1;//终止字符位置
				if (s[i] == s[j] && dp[i + 1][j- 1] == 1)
				{
					dp[i][j] = 1;
					start = i;
					max = l;
				}
			}
		}
		return s.substr(start, max); //返回最长回文子串
	}
};
void main()
{
	Solution* object = new Solution();
	string str;
	getline(cin, str);
	string res = object->longestPalindrome(str);
	cout << res << endl;
}

 

你可能感兴趣的:(Leetcode编程题)