From 4c29b90e4221ab1381758b92dc4628dae8a27a68 Mon Sep 17 00:00:00 2001 From: nidhibudhraja Date: Fri, 18 Oct 2019 18:22:17 +0530 Subject: [PATCH] longestPalin.cpp Longest palindrome algorithm --- DP/longestPalin.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 DP/longestPalin.cpp diff --git a/DP/longestPalin.cpp b/DP/longestPalin.cpp new file mode 100644 index 00000000..bfae9639 --- /dev/null +++ b/DP/longestPalin.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string expand(const string &s, int left, int right){ + const size_t n = s.length(); + while(left >= 0 && right < n && s[left] == s[right]) left--, right++; + return s.substr(left + 1, right - left - 1); + } + string longestPalindrome(string s) { + const size_t n = s.length(); + if(n == 0) return ""; + string res = s.substr(0, 1), temp; + for(int i = 0; i < n - 1; ++i){ + temp = expand(s, i, i); + if(temp.length() > res.length()) res = temp; + temp = expand(s, i, i + 1); + if(temp.length() > res.length()) res = temp; + } + return res; + } +};