Created
December 15, 2015 22:06
-
-
Save wangbj/6f250279e50854b9fcd9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static bool cache[1024][1024]; | |
class Solution { | |
public: | |
std::string longestPalindrome(std::string s) { | |
int sz = (int)s.size(); | |
if (sz == 0) return s; | |
int start = 0, len = 1; | |
memset(cache, 0, sizeof(cache)); | |
for (auto i = 0; i < sz; i++) { | |
cache[i][i] = 1; | |
} | |
for (auto i = 0; i < sz - 1; i++) { | |
auto j = 1 + i; | |
if (s[i] == s[j]) { | |
cache[i][j] = 1; | |
start = i; | |
len = 2; | |
} | |
} | |
for (auto k = 2; k < sz; k++) { | |
for (auto i = 0; i < sz - k; i++) { | |
auto j = i + k; | |
auto p = cache[i+1][j-1]; | |
if (p) { | |
if (s[i] == s[j]) { | |
cache[i][j] = 1; | |
if (j-i+1 > len) { | |
start = i; | |
len = (j-i+1); | |
} | |
} | |
} | |
} | |
} | |
return s.substr(start, len); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment