From 061ad70e40d75274b8c5df46350ab8e538211f24 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sat, 25 Nov 2023 10:14:47 -0700 Subject: [PATCH] day 43: 5-longest-palindromic-substring --- 5-longest-palindromic-substring/driver.cpp | 10 ++++ 5-longest-palindromic-substring/soln.cpp | 54 ++++++++++++++++++++++ 5-longest-palindromic-substring/soln.hpp | 8 ++++ 3 files changed, 72 insertions(+) create mode 100644 5-longest-palindromic-substring/driver.cpp create mode 100644 5-longest-palindromic-substring/soln.cpp create mode 100644 5-longest-palindromic-substring/soln.hpp diff --git a/5-longest-palindromic-substring/driver.cpp b/5-longest-palindromic-substring/driver.cpp new file mode 100644 index 0000000..58bf4db --- /dev/null +++ b/5-longest-palindromic-substring/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + string s = "varorant"; + string answer = "arora"; + Solution soln; + cout << "Found longest palindromic substring correctly? " << soln.test(s, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/5-longest-palindromic-substring/soln.cpp b/5-longest-palindromic-substring/soln.cpp new file mode 100644 index 0000000..1361b30 --- /dev/null +++ b/5-longest-palindromic-substring/soln.cpp @@ -0,0 +1,54 @@ +#include "soln.hpp" + +string Solution::longestPalindrome(string s) +{ + int n = s.size(); + + // base cases + if (n == 0) + return ""; + if (n == 1) + return s; + + // DP memorization table indices are substring start-end pairs + vector> dp(n, vector(n, false)); + + // single length strings/characters are palindromes + for (int i = 0; i < n; i++) + { + dp[i][i] = true; + } + + // start from first character + string ans = s.substr(0, 1); + + // start from last, decrease + for (int start = n - 1; start >= 0; start--) + { + // for each, end at last, increase + // so we go through the string's substrings from the end + for (int end = start + 1; end < n; end++) + { + if (s[start] == s[end]) + { + // either two characters, or extension of existing palindrome + if (end - start == 1 || dp[start + 1][end - 1]) + { + // mark as palindrome + dp[start][end] = true; + // check if larger + if (ans.size() < end - start + 1) + { + ans = s.substr(start, end - start + 1); + } + } + } + } + } + return ans; +} + +bool Solution::test(string s, string answer) +{ + return longestPalindrome(s) == answer; +} diff --git a/5-longest-palindromic-substring/soln.hpp b/5-longest-palindromic-substring/soln.hpp new file mode 100644 index 0000000..b2cafa9 --- /dev/null +++ b/5-longest-palindromic-substring/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + string longestPalindrome(string s); + bool test(string s, string answer); +}; \ No newline at end of file