您的位置:首页 > 其它

leetcode——5——Longest Palindromic Substring

2016-04-13 16:51 155 查看
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.

class Solution {
public:
string str_helper(string s, int left, int right)
{
int n = s.length();
while(left>=0 && right<=n-1 && s[left]==s[right]){
left--;
right++;
}
return s.substr(left+1, right-left-1);

}
string longestPalindrome(string s) {
if(s.length() <= 1)
return s;
string longest = s.substr(0,1);
for (int i=0; i<s.length(); i++){

string tmp = str_helper(s, i, i);
if (tmp.length() > longest.length())  {
longest = tmp;
}
tmp = str_helper(s, i, i+1);
if (tmp.length() > longest.length()) {
longest = tmp;
}
}

return longest;
}

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