求字符串的最长回文子串。
【思路】
1.从两边开始向中间发展
2.从中间开始向两边发展
3.从中间开始的变体,较为复杂,详见http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
【other code1-思路2】
string longestPalindrome(string s) { int n=s.size(); if(n==0) return ""; string re=s.substr(0,1); for(int i=0; i<n; i++){ string p1=testPalindrome(s,i,i); if(p1.size()>re.size()) re=p1; string p2=testPalindrome(s,i,i+1); if(p2.size()>re.size()) re=p2; } return re; } string testPalindrome(string s, int c1, int c2){ int l=c1; int r=c2; int n=s.size(); while(l>=0&&r<=n-1&&s[l]==s[r]){ l--; r++; } return s.substr(l+1,r-l-1); }
【结果1】
时间是O(n^2),100+ms,排名靠后。
【other code2-思路3】
// Transform S into T. // For example, S = "abba", T = "^#a#b#b#a#$". // ^ and $ signs are sentinels appended to each end to avoid bounds checking string preProcess(string s) { int n = s.length(); if (n == 0) return "^$"; string ret = "^"; for (int i = 0; i < n; i++) ret += "#" + s.substr(i, 1); ret += "#$"; return ret; } string longestPalindrome(string s) { string T = preProcess(s); int n = T.length(); int *P = new int[n]; int C = 0, R = 0; for (int i = 1; i < n-1; i++) { int i_mirror = 2*C-i; // equals to i‘ = C - (i-C) P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0; // Attempt to expand palindrome centered at i while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) P[i]++; // If palindrome centered at i expand past R, // adjust center based on expanded palindrome. if (i + P[i] > R) { C = i; R = i + P[i]; } } // Find the maximum element in P. int maxLen = 0; int centerIndex = 0; for (int i = 1; i < n-1; i++) { if (P[i] > maxLen) { maxLen = P[i]; centerIndex = i; } } delete[] P; return s.substr((centerIndex - 1 - maxLen)/2, maxLen); }
【结果2】
时间是O(n), 12ms,排名第一
为毛中档的题目就这么难! (? •?_•?)?┻━┻
下午分析。
时间: 2024-11-13 01:32:50