題目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
思路:
採用簡單暴力的遍歷搜索方式,分析題目的迴文形式,可分爲兩種:單數迴文和雙數迴文。在遍歷的過程中,不斷進行迴文檢測,更新最大的迴文子串的長度,記錄相應的索引。
代碼:
/*
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
*/
#include <string>
using namespace std;
class Solution {
// 迴文檢測算法函數
void longestPalindrome(const string& s, int a, int b, int& start, int& last)
{
// 字符串總長度
int len = s.size();
// 在起始索引處向兩側擴張地檢測索引
while (a >= 0 && b < len && s[a] == s[b])
{
a--;
b++;
}
// 將回文的索引設置爲正確的位置
a++;
b--;
// 如果當前的迴文長度大於歷史迴文長度,則更換回文子串前後索引
if (b - a > last - start)
{
start = a;
last = b;
}
}
public:
string longestPalindrome(string s) {
// 字符串總長度
int len = s.size();
// 判斷若爲空串,直接返回此空串
if (len == 0)
return s;
// 創建迴文的起始和終止索引
int start = 0, last = 0;
// 一次遍歷
for (int i = 0; i < len - 1; i++)
{
// 單數的迴文長度檢測
longestPalindrome(s, i, i, start, last);
// 雙數的迴文長度檢測
longestPalindrome(s, i, i + 1, start, last);
}
//返回迴文字符串
return s.substr(start, last - start + 1);
}
};