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; } }
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; }
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; } };
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
LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45536431