1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <iostream> #include <vector> #include <string> using namespace std;
class Solution { public: string longestPalindrome(string s) { string res; for (int i = 0; i < s.size(); i++) { string s1 = check(s, i, i); string s2 = check(s, i, i+1); res = res.size() > s1.size() ? res : s1; res = res.size() > s2.size() ? res : s2; }
return res; }
string check(const string& s, int l, int r) { while (l >= 0 && r < s.size() && s[l] == s[r]) { l--, r++; } return s.substr(l+1, r-l-1); } };
class Solution_2 { public: string longestPalindrome(string s) { int n = s.size(); vector<vector<int>> f(n+1, vector<int>(n+1, 0)); int start = 0, length = 0;
for (int len = 1; len <= n; len++) { for (int i = 0; i+len-1 < n; i++) { int l = i, r = i+len-1; if (len == 1) { f[l][r] = 1; } else if (len == 2) { f[l][r] = (s[l] == s[r]); } else { f[l][r] = f[l+1][r-1] && (s[l] == s[r]); }
if (f[l][r] != 0 && length < r-l+1) { start = l; length = r-l+1; } } } return s.substr(start, length); } };
int main() { Solution solution; vector<string> s_cases = { "babad", "cbbd" };
for (auto s : s_cases) { cout << "Input: \"" << s << "\"" << endl; string result = solution.longestPalindrome(s); cout << "Output: \"" << result << "\"" << endl; }
return 0; }
|