Leetcode實戰: 5. 最長迴文子串

題目:

給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。

示例1

輸入: "babad"
輸出: "bab"
注意: "aba" 也是一個有效答案。

示例2

輸入: "cbbd"
輸出: "bb"

算法實現:中心擴散法

class Solution {
public:
	string longestPalindrome(string s) {
		int length(1), i(1), j(0);
		int size = s.size();
		unordered_set<char> set;
		if (size == 1 || size == 0)
			return s;
		string output = "a";
		output[0] = s[0];
		for (; i < size; i++) {
			if (s[i] == s[i - 1]) {
				length++;
				j = i + 1;
				while (j - length - 1 >= 0 && s[j] == s[j - length - 1]) {
					length += 2;
					j++;
				}
				if (output.size() < length)	output = s.substr(j - length, length);
				length = 1;
			}
			if (i - length - 1 >= 0 && i >= 2 && s[i] == s[i - length - 1]) {
				length += 2;
				j = i + 1;
				while (j - length - 1 >= 0 && s[j] == s[j - length - 1]) {
					length += 2;
					j++;
				}
				if (output.size() < length)	output = s.substr(j - length, length);
				length = 1;
			}
		}
		return output;
	}
};

結果:

在這裏插入圖片描述

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