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.
stupid method:
int self_in_mid(string s, int index){ int length = 1; int size = s.length(); while((index-length >= 0) && (index + length < size)){ if(s[index-length] == s[index + length]) length ++; else break; } return (length - 1)*2 + 1; } int self_with_left(string s, int index){ int length = 1; int size = s.length(); while((index-length >= 0) && (index + length -1 < size)){ if(s[index-length] == s[index + length - 1]) length ++; else break; } return (length - 1)*2; } string longestPalindrome(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if(s.length() < 2) return s; int ssize = s.length(); int maxposition1 = 1; int maxlength1 = 1; int maxposition2 = 1; int maxlength2 = 0; for(int i = 1; i < ssize; ++i){ int tmp = self_in_mid(s,i); if(tmp > maxlength1){ maxlength1 = tmp; maxposition1 = i; } tmp = self_with_left(s,i); if(tmp > maxlength2){ maxlength2 = tmp; maxposition2 = i; } } if(maxlength1 > maxlength2) return s.substr(maxposition1 - (maxlength1-1)/2, maxlength1); else return s.substr(maxposition2 - maxlength2/2, maxlength2); }
下面的这段代码在leetcode上面运行报error:
然后我就想在本地调试,看看哪出问题了,同样的代码添加了两行输出之后在本机运行,输出为:
同样的代码不同的输出!这是哪出问题了?没想通。。。
class Solution { public: char S[2002]; int P[2002]; string longestPalindrome(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int ssize = s.length(); int slength = 0; S[slength++] = '$'; for(int i = 0; i < ssize; ++i){ S[slength++] = '#'; S[slength++] = s[i]; } S[slength] = '#'; int id = 0; int mx = 0; for(int i = 1; i < slength; ++i){ if(mx > i) P[i] = P[2*id-i] < (mx-i) ? P[2*id-i] : (mx-i); else P[i] = 1; while(S[i-P[i]] == S[i+P[i]]) ++P[i]; if(i+P[i]>mx){mx = i+P[i]; id = i;} } mx = 1; for(int i = 1; i < slength; ++i) if(P[i]>mx) { mx = P[i]; id = i; } --mx; return s.substr((id-mx+1)/2-1, mx); } };
add codes as follows, it is Accepted!
memset(P,0,sizeof(int)*2002); memset(S,'0',sizeof(char)*2002);
class Solution { public: char S[2002]; int P[2002]; string longestPalindrome(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function memset(P,0,sizeof(int)*2002); memset(S,'0',sizeof(char)*2002); int ssize = s.length(); int slength = 0; S[slength++] = '$'; for(int i = 0; i < ssize; ++i){ S[slength++] = '#'; S[slength++] = s[i]; } S[slength] = '#'; int id = 0; int mx = 0; for(int i = 1; i < slength; ++i){ if(mx > i) P[i] = P[2*id-i] < (mx-i) ? P[2*id-i] : (mx-i); else P[i] = 1; while(S[i-P[i]] == S[i+P[i]]) ++P[i]; if(i+P[i]>mx){mx = i+P[i]; id = i;} } mx = 1; for(int i = 1; i < slength; ++i) if(P[i]>mx) { mx = P[i]; id = i; } --mx; return s.substr((id-mx+1)/2-1, mx); } };