leetcode-n.Find the Longest Palindrome

题目

给一个字符串,找出里面最长的回文

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
"bab" and "aba"

思路

先把所有的回文找出来,然后比较其长度,输出最大的

找回文的过程通过先找"AA"或者"ABA",然后扩展两端直到找到其最大长度

代码

#include "stdafx.h"
#include <string>
using namespace std;

struct palindrome {
	int start;
	int end;
	int length;
};
class Slolution {
public:
	palindrome findPalindrome(string s) {
		palindrome pal_result;
		pal_result.length = 0;

		for (int i = 0; i < s.length()-1; i++) {
			if (s[i] == s[i + 1]) {
				int len=1;
				while ((i - len) > 0 && (i + len + 1) < s.length()) {
					if (s[i - len] == s[i + len + 1]) {
						len++;
					}
					else {
						break;
					}
				}
				if (2 * len > pal_result.length){
					pal_result.start = i - len + 1;
					pal_result.end = i + len;
					pal_result.length = 2 * len;
				}
			}
		}
		for (int i = 0; i < s.length() - 2; i++) {
			if (s[i] == s[i + 2]) {
				int len = 1;
				while ((i - len) > 0 && (i + len + 2) < s.length()) {
					if (s[i - len] == s[i + len + 2]) {
						len++;
					}
					else {
						break;
					}
				}
				if (2 * len + 1 > pal_result.length) {
					pal_result.start = i - len + 1;
					pal_result.end = i + len + 1;
					pal_result.length = 2 * len + 1;
				}
			}
		}
		return pal_result;
	}
};

int main()
{
	string input = "absdwejfisuyizwoeinbvggvbnwoeiappaauuyttyuuaappakxm";
	Slolution solution;
	palindrome result = solution.findPalindrome(input);
	
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_25379821/article/details/81779007