Longest Palindromic Substring
A.題意
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
題目的要求是給你一個字符串s(s最長的時候長度1000),要你找出這個字符串的最長子串。
B.思路
對於這道題我採用動態規劃的思路,用表格記錄第i個字符到第j個字符是否爲迴文串,然後從1到size檢測以每個字符開頭的某個長度字符串是否爲迴文串,藉助剛剛那個表格,如果檢測的子串頭尾相同且根據表格該子串除頭尾後爲迴文串則該子串爲迴文串
C.代碼實現
class Solution {
public:
string longestPalindrome(string s) {
bool table[1000][1000] = {false};
int size = s.length();
int max = 1;
int start = 0;
for (int i = 0;i < size;i++)
{
table[i][i] = true;
}
for (int len = 2;len <= size;len++)
{
for (int i = 0;i < size - len + 1;i++)
{
int j = i + len - 1;
if (len == 2 && s[i] == s[j])
{
table[i][j] = true;
start = i;
max = len;
}
else if(s[i] == s[j] && table[i + 1][j - 1])
{
table[i][j] = true;
start = i;
max = len;
}
}
}
return s.substr(start,max);
}
};