求最大回文子串長度的一種方法(非最優,時間複雜度爲O(N^2))

#include "iostream"
#include "string"
#include "sstream"
#include "vector"
#include "algorithm"
using namespace std;

int LongestPalindrome1(string s, int n)
{
	int i, j, max, c;
	if (s =="" || n < 1)
		return 0;
	max = 0;

	for (i = 0; i < n; ++i) { // i is the middle point of the palindrome  
		for (j = 0; (i - j >= 0) && (i + j < n); ++j) { // if the length of the palindrome is odd  
			if (s[i - j] != s[i + j])
				break;
			c = j * 2 + 1;
		}
		if (c > max)
			max = c;
		for (j = 0; (i - j >= 0) && (i + j + 1 < n); ++j) { // for the even case  
			if (s[i - j] != s[i + j + 1])
				break;
			c = j * 2 + 2;
		}
		if (c > max)
			max = c;
	}
	return max;
}
int LongestPalindrome2(string str)
{
	int length = 0;
	int max_len = 0;
	int left = 0; int right = 0;
	for (int i = 0; i < str.length(); i++)
	{
		//迴文長度爲奇數
		length = 1;
		left = i - 1;
		right = i + 1;
		while (left >= 0 && right < str.length() && str[left] == str[right])
		{
			length += 2;
			left--;
			right++;
		}
		if (length > max_len)
		{
			max_len = length;
		}
		//迴文長度爲偶數
		length = 0;
		left = i;
		right = i + 1;
		while (left >= 0 && right < str.length() && str[left] == str[right])
		{
			length += 2;
			left--;
			right++;
		}
		if (length > max_len)
			max_len = length;
	}
	return max_len;
}
int main()
{
	string str = "";

	while (getline(cin, str))
	{
		int max_len =  LongestPalindrome2(str);
		
		cout << max_len << endl;
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章