# [译]最长回文子串(Longest Palindromic Substring) Part I

[译]最长回文子串(Longest Palindromic Substring) Part I

+BIT祝威+悄悄在此留下版了个权的信息说：

# 一个常见的错误

 翻转S成为S’。查找S和S’最长公共子串，就是S的最长回文子串。

S和S’的最长公共子串是”aba”，确实是S的最长回文子串。

S=”abacdfgdcaba”，S’=”abacdgfdcaba”。

S和S’的最长公共子串是”abacd”，不过很明显这不是回文。

# 动态规划法O(N2)时间O(N2)空间

 1 string longestPalindromeDP(string s) {
2   int n = s.length();
3   int longestBegin = 0;
4   int maxLen = 1;
5   bool table[1000][1000] = {false};
6   for (int i = 0; i < n; i++) {
7     table[i][i] = true;
8   }
9   for (int i = 0; i < n-1; i++) {
10     if (s[i] == s[i+1]) {
11       table[i][i+1] = true;
12       longestBegin = i;
13       maxLen = 2;
14     }
15   }
16   for (int len = 3; len <= n; len++) {
17     for (int i = 0; i < n-len+1; i++) {
18       int j = i+len-1;
19       if (s[i] == s[j] && table[i+1][j-1]) {
20         table[i][j] = true;
21         longestBegin = i;
22         maxLen = len;
23       }
24     }
25   }
26   return s.substr(longestBegin, maxLen);
27 }

# 更简单的算法O(N2)时间O(1)空间

 1 string expandAroundCenter(string s, int c1, int c2) {
2   int l = c1, r = c2;
3   int n = s.length();
4   while (l >= 0 && r <= n-1 && s[l] == s[r]) {
5     l--;
6     r++;
7   }
8   return s.substr(l+1, r-l-1);
9 }
10
11 string longestPalindromeSimple(string s) {
12   int n = s.length();
13   if (n == 0) return "";
14   string longest = s.substr(0, 1);  // a single char itself is a palindrome
15   for (int i = 0; i < n-1; i++) {
16     string p1 = expandAroundCenter(s, i, i);
17     if (p1.length() > longest.length())
18       longest = p1;
19
20     string p2 = expandAroundCenter(s, i, i+1);
21     if (p2.length() > longest.length())
22       longest = p2;
23   }
24   return longest;
25 }

+BIT祝威+悄悄在此留下版了个权的信息说：

PS：“中心检测法”是我胡诌的名字。

# 提问O(N)

Thank you for your kindly donation!
 微信捐赠二维码： Donate by microMsg:
posted @ 2014-12-14 16:05  BIT祝威  阅读(3715)  评论(3编辑  收藏  举报