资质有限,所以我就只好,写了一个非常差的example,而且我这个也不能保证从这个字符串中
返回来的是一个非常的长的回文子串。
class Solution { public: string longestPalindrome(string s) { int sizenum = s.size(); if(sizenum < 2)return NULL; //string min_s = NULL; int sign_i = 0; int sign_j = 0; for(int i = 0;i < sizenum;i++){ for(int j=sizenum - 1;j > i;j--){ if(s[i] == s[j]){ sign_i = i; sign_j = j; while(sign_i != sign_j && s[sign_i] == s[sign_j] && sign_i < sign_j){ sign_i ++; sign_j --; } if( sign_i == sign_j || sign_i > sign_j){ int sign_size = j - i + 1; string min_s = s.substr(i,sign_size); return min_s; } } } } return NULL; } };
从leetcode上找了一个非常好的例子
下面贴出来代码:
class Solution { public: string longestPalindrome(string s) { int start = 0, end = 0, len = 0, g_start = 0, i = 0, n = s.size(); while(i<n) { start = i, end = i; while(i+1<n && s[end] == s[end+1]) end++ ; i = end + 1; while(start-1>=0 && end+1<n && s[end+1] == s[start-1]) { start-- ; end++ ; } if(end - start + 1 > len) { len = end - start + 1; g_start = start; } } cout<<s.substr(g_start, len); return s.substr(g_start, len); } };
class Solution {
public:
string longestPalindrome(string s) {
int sizenum = s.size();
if(sizenum < 2)return NULL;
//string min_s = NULL;
int sign_i = 0;
int sign_j = 0;
for(int i = 0;i < sizenum;i++){
for(int j=sizenum - 1;j > i;j--){
if(s[i] == s[j]){
sign_i = i;
sign_j = j;
while(sign_i != sign_j &&
s[sign_i] == s[sign_j] &&
sign_i < sign_j){
sign_i ++;
sign_j --;
}
if( sign_i == sign_j || sign_i > sign_j){
int sign_size = j - i + 1;
string min_s = s.substr(i,sign_size);
return min_s;
}
}
}
}
return NULL;
}
};