首页 > 其他 > 详细

Longest Palindromic Substring--LeetCode

时间:2015-04-01 09:28:34      阅读:210      评论:0      收藏:0      [点我收藏+]

题目:

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> 
#include <vector>
using namespace std;
/*
一个字符串中最长的回文子串 
思路:以某一个字符为中心开始向两边遍历 这样查找最长的子串 
*/
int LongestPalindromicSub(string& str)
{
	int pre,next,i;
	int maxlen=0;
	int pos;
	for(i=0;i<str.length();i++)
	{
		pre =i-1;
		next = i+1;
		while(pre>=0 && next<str.length())
		{
			if(str[pre] == str[next])
			{
				pre--;
				next++;
			}
			else
				break;
		}
		if(maxlen < (i-pre)*2+1)
		{
			maxlen = next-pre-1;
			pos = pre+1;
		}
			
	}
//	cout<<pos<<endl;
	return maxlen;
} 
int main() 
{
	string str("ADOEBEOODEBEDCAAACDABDDBDAD");
	cout<<LongestPalindromicSub(str)<<endl;
	return 0;
}



Longest Palindromic Substring--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/44802073

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!