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
| #include <iostream> #include <vector> #include <string> using namespace std;
class Solution { public: string longestPalindrome(string s) { if (s.empty()) { return ""; }
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 = -1, length = 0;
for (int i = n; i >= 1; i--) { for (int j = i; j <= n; j++) { f[i][j] = s[i-1] == s[j-1] && (j - i < 2 || f[i+1][j-1]); if (f[i][j] != 0 && length < j - i + 1) { start = i; length = j - i + 1; } } }
return s.substr(start - 1, length); } };
int main() { vector<string> test_cases = { "babad", "cbbd" };
for (auto s : test_cases) { Solution solution; cout << "Input: " << s << endl; string result = solution.longestPalindrome(s); cout << "Output: " << result << endl; }
return 0; }
|