Skip to content

Instantly share code, notes, and snippets.

@DragonOsman
Last active February 13, 2022 20:54
Show Gist options
  • Save DragonOsman/4045d1f9270be1b0c51d70c4ed0ddebc to your computer and use it in GitHub Desktop.
Save DragonOsman/4045d1f9270be1b0c51d70c4ed0ddebc to your computer and use it in GitHub Desktop.
#include <vector>
#include <algorithm>
#include <string_view>
class Solution {
public:
string longestPalindrome(string s) {
std::size_t s_length{ s.length() };
string longest_palindrome;
// i == start index, j == end index
for (std::size_t i{}; i <= s_length; ++i)
{
for (std::size_t j{i}; j <= s_length; ++j)
{
string_view s_view{s};
string_view substr_view{s_view.substr(i, j - i)};
if (substr_view.length() >= 2 && std::equal(substr_view.begin(), substr_view.end(), substr_view.rbegin()))
{
if (static_cast<int>(substr_view.length()) > longest_palindrome.length())
{
longest_palindrome = substr_view;
}
}
}
}
if (longest_palindrome == "")
{
string str{s[0]};
longest_palindrome = str;
}
return longest_palindrome;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment