1. 程式人生 > >LeetCode——5.Longest Palindromic Substring

LeetCode——5.Longest Palindromic Substring

1.題目詳情

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 給出一個字串s,找到s中最長的一個迴文串。可以假設s的最大長度為1000。

Example 1:

Input: “babad” Output: “bab” Note: “aba” is also a valid answer.

Example 2:

Input: “cbbd” Output: “bb”

完善下面的程式碼:

class Solution {
public:
    string longestPalindrome(string s) {
        
    }
};

2.解題方法

迴文串是指一個字串的反轉字串還是和原來的一樣,比如"aba"和"abba",即從中間看回文串是對稱的。所以這裡的解題思路就是從迴文串的中間這一關鍵點落手。遍歷字串s,從每一處字元開始往兩邊看,找到以這處字元為中心的迴文串。當然還要考慮特殊情況,像上面的"abba"的中間的兩個’b’一樣。

class Solution {
public:
	 string longestPalindrome(string s) {
		 int size = s.size();
		 int start = 0;
		 int maxLength = 0;
		 string maxLengthStr;
		 while (start < size) {
		 	int left = start - 1;
		 	int right = start + 1;
		 	int length = 1;
		 	while (s[left] == s[right] && left >= 0 && right < size) {
		 		length = length + 2;
		 		left = left - 1;
		 		right = right + 1;
		 	}
		 	if (length > maxLength) {
		 		maxLength = length;
		 		maxLengthStr = s.substr(left + 1, right - left - 1);
		 	}
		 	length = 0;
		 	left = start;
		 	right = start + 1;
		 	while (s[left] == s[right] && left >= 0 && right < size) {
		 		length = length + 2;
		 		left = left - 1;
		 		right = right + 1;
		 	}
		 	if (length > maxLength) {
		 		maxLength = length;
		 		maxLengthStr = s.substr(left + 1, right - left - 1);
		 	}
		 	start = start + 1;
		 }
		 return maxLengthStr;
	 }
};

最終執行時間是8ms。