您的位置:首页 > 其它

leetcode Longest Palindromic Substring

2015-09-22 16:24 489 查看


Longest Palindromic Substring

My Submissions

Question
Solution

Total Accepted: 70417 Total
Submissions: 338025 Difficulty: Medium

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.

Show Tags

Show Similar Problems

Have you met this question in a real interview?
Yes

No

Discuss

算法转自http://www.cnblogs.com/caterpillarofharvard/articles/4245626.html,但是由于本人理解力切佳,所以就在纸上画了画。







代码如下:

// test5LongestPalindromicSubstring.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "string"
#include "vector"

using std::string;
using std::vector;

string longPalindrome(string s)
{
if (s.size() < 2)
return s;
int center=0, right=0;
int max = 0;
int j = 0;
int n = s.size();
vector<int> len;
int currentlen = 0;
len.push_back(1);
for (int i = 1; i < n; i++)
{
if (i <= right)
{
j = 2 * center - i;
if (len[j] + i < center)
{
currentlen = len[j];
len.push_back(currentlen);
continue;
}
}
currentlen = 0;
int l = i, r = i;
while (l >= 0 && r<n && s[l] == s[r])//注意此处,最后一个判定条件必须放到后面的后面,否则将会出错。
{
currentlen++;
r++;
l--;
}
len.push_back(currentlen);
if (currentlen > max)
{
center = i;
right = center + currentlen - 1;
max = currentlen;
}
}

string result = "";
int left = center - max + 1;
if (left % 2 == 0)
left++;
while (left<right)
{
result += s[left];
left+=2;
}
return result;

}

string longestPalindrome(string s)
{
if (s.size() < 2)
return s;
string temp = "#";
for (int i = 0; i < s.size(); i++)
{
temp += s[i];
temp += '#';
}
return longPalindrome(temp);
}

int _tmain(int argc, _TCHAR* argv[])
{
string s = longestPalindrome("aaaba");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: