aboutsummaryrefslogtreecommitdiff
path: root/longest_palindromic_substr.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /longest_palindromic_substr.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'longest_palindromic_substr.cpp')
-rw-r--r--longest_palindromic_substr.cpp35
1 files changed, 35 insertions, 0 deletions
diff --git a/longest_palindromic_substr.cpp b/longest_palindromic_substr.cpp
new file mode 100644
index 0000000..4ecba25
--- /dev/null
+++ b/longest_palindromic_substr.cpp
@@ -0,0 +1,35 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ string longestPalindrome(string s) {
+ if (s.size() == 0)
+ return "";
+ int i = 0, j = 0, n = s.size();
+ bool p[n][n] = {false};
+ for (int x = 0; x < n; x++) {
+ p[x][x] = true;
+ if (x == n - 1)
+ break;
+ p[x][x + 1] = (s[x] == s[x + 1]);
+ }
+ for (int i = n - 3; i >= 0; --i)
+ for (int j = i + 2; j < n; ++j)
+ p[i][j] = (p[i + 1][j - 1] && s[i] == s[j]);
+ int max = 0;
+ string ans = "";
+ for (int i = 0; i < n; i++)
+ for (int j = i; j < n; j++)
+ if (p[i][j] == true && j - i + 1 > max) {
+ max = j - i + 1;
+ ans = s.substr(i, j - i + 1);
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ string s = "babad";
+ cout << obj.longestPalindrome(s);
+}