您的位置:首页 > 其它

leetCode:Longest Palindromic Substring

2014-09-25 13:15 447 查看
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of
S is 1000, and there exists one unique longest palindromic substring

#include<iostream>
#include<string>
using namespace std;
class Solution{
public:
string longestPalindrome1(string s);
};

string Solution::longestPalindrome1(string s){
int start=0;
int maxlength=1;
string res;
if(s.length()==1) return s;

int low,high;
for(int i=1;i<s.length();++i){
low = i - 1;
high = i;
while (low >= 0 && high < s.length() && s[low] == s[high]){
if (high - low + 1 > maxlength){
start = low;
maxlength = high - low + 1;
}
--low;
++high;
}
low = i - 1;
high = i + 1;
while (low >= 0 && high <s.length() && s[low] == s[high])
{
if (high - low + 1 > maxlength)
{
start = low;
maxlength = high - low + 1;
}
--low;
++high;
}

res = s.substr(start,maxlength);
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: