Wobei... hauptsächlich stört:
* dass du recht unsprechende Variablennamen verwendest
* dass get_longest_pal zwei dinge macht die ich persönlich auftrennen würde:
das längste palindrom suchen das bei l, middle_indel, r anängt
gucken ob es länger als das bisher gefundene längste palindrom ist und ggf. longest_pal updaten
Dass du pal während der Suche zusammenbaust verwirrt auch eher.
Nach ein paar kleinen Umbauten sieht dein Code so aus, was ich persönlich besser zu lesen finde:
string get_longest_palindrome_at(string const& s, int left_index, int right_index)
{
assert(left_index + 1 == right_index || left_index + 2 == right_index);
// check if there is a palindrome with that center position (mid-point between left_index and right_index) at all
if (s[left_index] != s[right_index])
return "";
// extend bounds as much as possible
while (left_index > 0 && (right_index + 1) < s.size())
{
if (s[left_index - 1] == s[right_index + 1])
{
left_index--;
right_index++;
}
else
break;
}
return string(s.begin() + left_index, s.begin() + right_index + 1);
}
void update_longest_palindrome(string const& s, int left_index, int right_index, string& longest_palindrome)
{
// update longest_palindrome by comparing with the longest palindrome with the specified
// center position (mid-point between left_index and right_index)
if (left_index >= 0 && right_index < s.size())
{
string const candidate = get_longest_palindrome_at(s, left_index, right_index);
if (candidate.size() > longest_palindrome.size())
longest_palindrome = candidate;
}
}
string find_longest_palindrome(string const& s)
{
string longest_palindrome;
for (int i = 0; i < s.size(); i++)
{
// pair element in the middle
update_longest_palindrome(s, i, i + 1, longest_palindrome);
// single element in the middle
update_longest_palindrome(s, i, i + 2, longest_palindrome);
}
return longest_palindrome;
}