From e8e1e3461acfebeaf5aef0ab45faa59b1ae411f0 Mon Sep 17 00:00:00 2001 From: aadarsh patwal <91589322+VIBEXD@users.noreply.github.com> Date: Fri, 14 Oct 2022 22:23:24 +0530 Subject: [PATCH] solution for longest palindromic subsequence --- longest-palindromic-subsequence.cpp | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 longest-palindromic-subsequence.cpp diff --git a/longest-palindromic-subsequence.cpp b/longest-palindromic-subsequence.cpp new file mode 100644 index 0000000..a8e7b7f --- /dev/null +++ b/longest-palindromic-subsequence.cpp @@ -0,0 +1,35 @@ +class Solution +{ +public: + int check(string &s, int L, int R) + { + while (L >= 0 and R < s.length() and s[L] == s[R]) + { + L--; + R++; + } + return R - L - 1; + } + + string longestPalindrome(string s) + { + + int ans = 0, st = 0; + int n = s.length(); + + for (int i = 0; i < n; i++) + { + int len1 = check(s, i, i); + int len2 = check(s, i, i + 1); + + int len = max(len1, len2); + + if (len > ans) + { + ans = len; + st = i - (len - 1) / 2; + } + } + return s.substr(st, ans); + } +}; \ No newline at end of file