Witam.
Mam takie zadanie: Dla podanego stringa s zwróć najdłuższy palindromiczny string zawarty w s.
Zrobiłem rozwiązanie O(n^3) gdzie n to długość stringa s, nawet zaliczyło mi to rozwiązanie, ale patrząc na statystyki:
Widać że te złożoność da się mocno poprawić. Widziałem jedno rozwiązanie używające programowania dynamicznego, ale też było O(n^2). Więc jak można to inaczej zrobić?
To mój obecny kod:
bool is_palindromic(const std::string& s, const size_t& start, const size_t& end) {
for (size_t i = start, j = end; i <= j; i++, j--) {
if (s[i] != s[j])
return false;
}
return true;
}
std::string longestPalindrome(std::string s) {
std::pair<uint32_t, uint32_t> max = { 0,0 };
for (uint32_t i = 0; i < s.size(); i++) {
uint32_t solution = 0;
for (uint32_t j = i + 1; j < s.size(); j++) {
if (is_palindromic(s, i, j)) {
solution = j;
}
}
if (i < solution && solution - i > max.second - max.first)
max = { i, solution };
}
std::string result = "";
for (uint32_t i = max.first; i <= max.second; i++)
result += s[i];
return result;
}