Skip to content

Commit

Permalink
Added Longest Palindromic SubString
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 3, 2023
1 parent b33002b commit 5c5dd77
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
33 changes: 32 additions & 1 deletion Medium/LongestPalindromicSubstring/include/solution.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

class Solution {
public:
static auto longest_palindrome(const std::string &s) -> std::string {
[[maybe_unused]] static auto longest_palindrome_tle(const std::string &s) -> std::string {
std::string ans;
std::size_t max_length = 0;

Expand All @@ -27,4 +27,35 @@ class Solution {

return ans;
}

static auto longest_palindrome(const std::string &s) -> std::string {
if (s.empty()) return { };

int32_t start = 0;
int32_t end = 0;

for (int32_t i = 0; i < s.length(); ++i) {
int32_t len1 = expand_around_center(s, i, i);
int32_t len2 = expand_around_center(s, i, i + 1);

int32_t len = std::max(len1, len2);

if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}

return s.substr(start, end - start + 1);
}

static auto expand_around_center(const std::string &s,
int32_t left, int32_t right) -> int32_t {
while (left >= 0 && right < s.length()
&& s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
};
2 changes: 1 addition & 1 deletion Medium/LongestPalindromicSubstring/tests/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ TEST_F(LongestPalindromicSubstring, FirstTest) {
std::string element = "babad";

std::string result = Solution::longest_palindrome(element);
std::string expected = "bab";
std::string expected = "aba";

ASSERT_EQ(result, expected);
}
Expand Down

0 comments on commit 5c5dd77

Please sign in to comment.