Problem:
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.
Solution:
以每一个字符为中间查找回文串,然后记录下最大的回文串,时间复杂度O(n^2)
题目大意:
给定一个字符串,求字符串的最长回文字串。
解题思路:
最容易想到暴力破解的方法,确定每一个子串,然后查看是否是回文串,时间复杂度O(n^3),容易超时,采用Solution中的方法,时间负责度克达到O(n^2),据说可以通过Manacher’s Algorithm算法来将时间复杂度提升到O(n),但是还没太明白意思,原文链接:http://blog.csdn.net/han_xiaoyang/article/details/11969497#t20
Java源代码(用时294ms,真是够长的):
public class Solution { public String longestPalindrome(String s) { int Max=1,Maxf=0,Maxe=0; for(int i=0;i<s.length();i++){ int end = findOdd(s,i); if(Max < (end-i)*2+1){ Max = (end-i)*2+1; Maxf = i+i-end; Maxe=end; } end = findEven(s,i); if(Max < (end-i)*2){ Max = (end-i)*2; Maxf = i+i+1-end; Maxe = end; } } return s.substring(Maxf,Maxe+1); } public int findOdd(String s,int center){ int i=center-1,j=center+1; while(i>=0 && j<s.length()){ if(s.charAt(i)!=s.charAt(j))return j-1; i--;j++; } return j-1; } public int findEven(String s,int center){ int i=center,j=center+1; while(i>=0 && j<s.length()){ if(s.charAt(i)!=s.charAt(j))return j-1; i--;j++; } return j-1; } }
C语言源代码(用时29ms):
int findOdd(char* s,int center){ int i=center-1,j=center+1; while(i>=0 && s[j]){ if(s[i]!=s[j])return j-1; i--;j++; } return j-1; } int findEven(char* s,int center){ int i=center,j=center+1; while(i>=0 && s[j]){ if(s[i]!=s[j]){ return j-1; } i--;j++; } return j-1; } char* longestPalindrome(char* s) { int i=0,end,Max=1,Maxf=0,Maxe=0; for(i=0;s[i];i++){ end=findOdd(s,i); if(Max<(end-i)*2+1){ Max=(end-i)*2+1; Maxf=i+i-end;Maxe=end; } end=findEven(s,i); if(Max<(end-i)*2){ Max=(end-i)*2; Maxf=i+i+1-end;Maxe=end; } } s[Maxe+1]=0; return s+Maxf; }
C++源代码(用时95ms):
class Solution { public: string longestPalindrome(string s) { int Max=1,Maxf=0,Maxe=0; for(int i=0;i<s.size();i++){ int end = findOdd(s,i); if(Max < (end-i)*2+1){ Max = (end-i)*2+1; Maxf=i+i-end; Maxe=end; } end = findEven(s,i); if(Max <(end-i)*2){ Max = (end-i)*2; Maxf=i+i+1-end; Maxe=end; } } return s.substr(Maxf,Max); } int findOdd(string s,int center){ int i=center-1,j=center+1; while(i>=0 && j<s.size()){ if(s[i]!=s[j])return j-1; i--;j++; } return j-1; } int findEven(string s,int center){ int i=center,j=center+1; while(i>=0 && j<s.size()){ if(s[i]!=s[j])return j-1; i--;j++; } return j-1; } };
Python源代码(用时1434ms,这个真心太长了,要改进算法):
class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): Max=1;Maxf=0;Maxe=0 for i in range(0,len(s)): end = self.findOdd(s,i) if Max < (end-i)*2+1: Max = (end-i)*2+1 Maxf = i+i-end Maxe = end end = self.findEven(s,i) if Max < (end-i)*2: Max = (end-i)*2 Maxf = i+i+1-end Maxe = end return s[Maxf:Maxe+1] def findOdd(self,s,center): i=center-1;j=center+1 while i>=0 and j<len(s): if s[i]!=s[j]:return j-1 i=i-1;j=j+1 return j-1 def findEven(self,s,center): i=center;j=center+1 while i>=0 and j<len(s): if s[i]!=s[j]:return j-1 i=i-1;j=j+1 return j-1
时间: 2024-10-11 21:01:30