最长字符串回文子串问题

给定一个字符串S,要求出它的最长回文子串。

比如,S="ababacdefaba",返回最长回文子串"ababa"。

实现方法如下:

由于回文串是左右对称的,我们以字符串S的每一个字符作为中心轴,比较其左右两边的字符是否相等,得到以其为中心的最大回文串,最终得到整个字符串S的最大回文字符串。

其实现代码如下所示:

#include
#include
#include
using namespace std;
string longestPalindrome1(string &s)//动态规划,时间复杂度O(n^2),空间复杂度O(n^2)
{
	int slen = s.length();
	if (slen == 0)
	{
		return "";
	}
	int maxfirst = 0; 
	int maxlength = 1;
	vector> dp(slen, vector(slen, false));
	int i, j, len;
	for (i = 0; i != slen; ++i)
	{
		dp[i][i] = true;
		if (i !=slen-1 && s[i] == s[i + 1])
		{
			dp[i][i + 1] = true;
			maxfirst = i;
			maxlength = 2;
		}
	}
	for (len = 3; len <= slen; ++len)
	{
		for (i = 0; i < slen - len + 1; ++i)
		{
			j = i + len - 1;
			dp[i][j] = dp[i + 1][j - 1] && s[i] == s[j];
			if (dp[i][j])
			{
				if (len > maxlength)
				{
					maxlength = len;
					maxfirst = i;
				}
			}
		}
	}
	return s.substr(maxfirst, maxlength);
}

string longestPalindrome2(string &s)//中心拓展法,时间复杂度O(n^2),空间复杂度O(1),优于动态规划法
{
	int slen = s.length();
	if (slen == 0)
	{
		return "";
	}
	int maxfirst = 0;
	int maxlength = 1;
	int left = 0;
	int right = 0;
	for (int i = 0; i != slen; ++i)
	{
		left = i - 1;
		right = i + 1;
		while (s[right] == s[i])
		{
			++right;
		}
		while (left >= 0 && right < slen && s[left] == s[right])
		{
			--left;
			++right;
		}
		int length = right - left - 1;
		if (length > maxlength)
		{
			maxfirst = left + 1;
			maxlength = length;
		}
	}
	return s.substr(maxfirst, maxlength);
}
int main()
{
	string s1 = "abcd";
	string s2 = "";
	string s3 = "abacd";
	string s4 = "ababababcdef";
	string s5 = "gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv";
	cout << longestPalindrome1(s1) << endl;
	cout << longestPalindrome1(s2) << endl;
	cout << longestPalindrome1(s3) << endl;
	cout << longestPalindrome1(s4) << endl;
	cout << longestPalindrome2(s5) << endl;
	system("pause");
	return 0;
}

实验结果如下所示,

最长字符串回文子串问题_第1张图片

你可能感兴趣的:(字符串操作)