题目(来源leetcode):
题目的意思就是从给定的字符串中找出一个最长的 对称 字符串
这道题,我的代码感觉写的贼烂,求大佬指点!
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
#Python版本
from collections import defaultdict
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
#dict_s=defaultdict(int)
#for i,x in enumerate(s):
# dict_s+=1
i=0
b=""
max=0
if s=="":
return ""
while(i<len(s)):
if len(s)-i-1>max:
for j in range(len(s)):
if s[len(s)-1-j] == s[i] and len(s)-j-i >max:
temp,isornot=self.Is_palindromic(s[i:len(s)-j])
if isornot and len(s)-j-i >max:
max=len(s)-j-i
b=temp
else:
continue
else:
continue
i+=1
else:
break
if b=="":
b=s[0]
return b
def Is_palindromic(self,s):
if len(s) %2 ==0:
#assert len(s[:len(s)//2][::-1]) == len(s[len(s)//2 :])
if s[:len(s)//2][::-1] == s[len(s)//2 :]:
return s,1
else:
return "",0
else:
if s[:len(s)//2][::-1]==s[len(s)//2+1:]:
return s,1
else:
return "",0
#C++版本
#include <cstring>
class Solution {
public:
string longestPalindrome(string s) {
int i,max;
i=0;
max=0;
string b="";
string temp="";
if(s==""){
return "";
}
while(i<s.size()){
if(s.size()-i > max){
for(int j=0;j <s.size();j++){
if(s[s.size()-1-j]==s[i] && s.size()-j-i >max){
temp=Is_palindrom(s.substr(i,s.size()-j-i));
if(temp != "" && s.size()-j-i >max){
max=s.size()-j-i;
b=temp;
}else{
continue;
}
}else{
continue;
}
}
i++;
}else{
break;
}
}
if(b.compare("")==0){
b=s[0];
}
return b;
}
string Is_palindrom(string s){
string b="";
string s1;
string s2;
if(s.size() % 2 == 0){
s1=s.substr(0,s.size()/2);
s2=s.substr(s.size()/2,s.size()/2);
reverse(s1.begin(),s1.end());
if(s1.compare(s2)==0){
//if(strrev(s1)==s2){
b=s;
}else{
b="";
}
}else{
s1=s.substr(0,int(s.size()/2));
s2=s.substr(int(s.size()/2 +1),s.size()-s.size()/2 -1);
reverse(s1.begin(),s1.end());
if(s1.compare(s2)==0){
//if(strrev(s1)==s2){
b=s;
}else{
b="";
}
}
return b;
}
};