标签:style blog http color io ar 使用 for sp
反转法: 反转S为S‘, 找到其中的最长公共子串s, 并确认子串s在S中的下标iS与在S‘中的下标iS‘是否满足式: length(S) = iS + iS‘ + length(s). 如果满足则s为搜索结果, 如果不满足我们就继续搜索.
1 class Solution {
2 public:
3 string longestPalindrome(string s) {
4 if (s.length() <= 1) return s;
5 // DP solution
6 bool P[1000][1000] = {false};
7 int start = 0;
8 int maxLen = 0;
9 for (int i = 0; i < s.length(); i++) {
10 P[i][i] = true;
11 }
12 for (int i = 0; i < s.length() - 1; i++) {
13 if (s[i] == s[i+1]) {
14 P[i][i+1] = true;
15 start = i;
16 maxLen = 2;
17 }
18 }
19 for (int len = 3; len <= s.length(); len++) {
20 for (int i = 0; i < s.length() - len + 1; i++) {
21 int j = i + len - 1;
22 if (s[j] == s[i] && P[i+1][j-1]) {
23 P[i][j] = true;
24 start = i;
25 maxLen = len;
26 }
27 }
28 }
29 return s.substr(start, maxLen);
30 }
31 };
1 class Solution {
2 public:
3 string longestPalindrome(string s) {
4 if (s.length() <= 1) return s;
5 string longest = s.substr(0, 1);
6 // Center Solution
7 for (int i = 0; i < s.length() - 1; i++) {
8 string res = expandFromCenter(s, i, i);
9 if (res.length() > longest.length()) longest = res;
10 res = expandFromCenter(s, i, i+1);
11 if (res.length() > longest.length()) longest = res;
12 }
13 return longest;
14 }
15
16 string expandFromCenter(string s, int l, int r) {
17 while (l >= 0 && r < s.length() && s[l] == s[r]) {
18 l--;
19 r++;
20 }
21 return s.substr(l+1, r-l-1);
22 }
23 };
Manacher法: 线性时间解法, 比较复杂, 戳.
标签:style blog http color io ar 使用 for sp
原文地址:http://www.cnblogs.com/lancelod/p/4047077.html