赞
踩
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),要你找出这个字符串的最长子串。
对于这道题我采用动态规划的思路,用表格记录第i个字符到第j个字符是否为回文串,然后从1到size检测以每个字符开头的某个长度字符串是否为回文串,借助刚刚那个表格,如果检测的子串头尾相同且根据表格该子串除头尾后为回文串则该子串为回文串
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);
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。