LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)
Problem:
Solution:
题目大意:
解题思路:
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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。