From 318dccf28e53f61aa419b6d073e6e064d3d6df1b Mon Sep 17 00:00:00 2001 From: Wander_lust Date: Thu, 29 Jan 2026 14:19:10 +0530 Subject: [PATCH] Add longestPalindrome function to find palindromes Implement a solution to find the longest palindromic substring using the expand from center technique. --- leetcode/lc5/ExpandCentre.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/leetcode/lc5/ExpandCentre.cpp b/leetcode/lc5/ExpandCentre.cpp index e69de29..723d445 100644 --- a/leetcode/lc5/ExpandCentre.cpp +++ b/leetcode/lc5/ExpandCentre.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + string longestPalindrome(string s) { + if (s.length() <= 1) { + return s; + } + + auto expand_from_center = [&](int left, int right) { + while (left >= 0 && right < s.length() && s[left] == s[right]) { + left--; + right++; + } + return s.substr(left + 1, right - left - 1); + }; + + string max_str = s.substr(0, 1); + + for (int i = 0; i < s.length() - 1; i++) { + string odd = expand_from_center(i, i); + string even = expand_from_center(i, i + 1); + + if (odd.length() > max_str.length()) { + max_str = odd; + } + if (even.length() > max_str.length()) { + max_str = even; + } + } + + return max_str; + } +};