Longest Palindromic Substring [leetcode] O (n ^ 2) DP and O (n) algorithms, longestsubstring
Two methods are implemented. One is DP, which is made of loops. recursion is easier.
string longestPalindrome(string s) { int n = s.size(); bool dp[1001][1001]; int maxl = 1; int maxs = 0; for (int i = n - 1; i >= 0; i--) { dp[i][i] = true; for (int j = i + 1; j < n; j++) { if (s[i] == s[j] && (j == i + 1 || dp[i + 1][j - 1])) { dp[i][j] = true; if (maxl < (j - i + 1)) { maxl = (j - i + 1); maxs = i; } } else dp[i][j] = false; } } return s.substr(maxs, maxl); }
Another method is the well-known O (n) method.
string longestPalindrome(string s) { int n = s.size(); int newn = n * 2 + 1; int p[2000]; char * news = new char[newn]; for (int i = 0; i < n; i++) { news[2 * i] = '*'; news[2 * i + 1] = s[i]; } news[2 * n] = '*'; //s:abac //news:*a*b*a*c* //P: 121412121 int mx = 0; int mi = 0; int maxLen = 0; int maxIndex = 0; for (int i = 0; i < newn; i++) { if (mx > i) p[i] = min(p[2 * mi - i], mx - i); else p[i] = 1; for (;i - p[i] >= 0 && i + p[i] < newn && news[i + p[i]] == news[i - p[i]];p[i]++); if (p[i] + i > mx) { mx = p[i] + i; mi = i; } if (maxLen < p[i] - 1) { maxLen = p[i] - 1; maxIndex = i; } } string returnVal = s.substr((maxIndex - maxLen) / 2, maxLen); delete [] news; return returnVal; }