The code below is my solution to the following problem (problem #5 on LeetCode):
Given a string s, return the longest palindromic substring in s.
I wonder whether my use of iterators is an overkill. They seem to be convenient for calculating the length of the ranges and for constructing the string in the answer. They also provide a standard way of dealing with an empty range.
I would also like to know whether I am on the right spot with tuples.
Any other comments about the coding style and the idiomatic use of C++ would be greatly appreciated!
class Solution {
// Return pair of iterators for the longest polindromic substring
// starting with i and j as center.
// The end iterator is one past the end of the range, like in STL.
// If s[i] != s[j], an empty range is returned.
// tuple is new in C++17
tuple<string::const_iterator, string::const_iterator>
polindromicRange(const string &s, int i, int j) {
if (j >= s.size() || s[i] != s[j]) return {s.begin(), s.begin()};
string::const_iterator begin = s.cbegin() + i;
string::const_iterator end = s.cbegin() + j + 1;
while (begin > s.begin() && end < s.end() && *(begin - 1) == *end) {
--begin;
++end;
};
return {begin, end};
}
void newLongestRange(const string &s, int i, int j,
string::const_iterator &longestBegin,
string::const_iterator &longestEnd) {
auto [begin, end] = polindromicRange(s, i, j);
if (end - begin > longestEnd - longestBegin) {
longestBegin = begin;
longestEnd = end;
}
}
public:
string longestPalindrome(string s) {
string::const_iterator longestBegin, longestEnd;
for (int i = 0; i < s.size(); ++i) {
newLongestRange(s, i, i, longestBegin, longestEnd);
newLongestRange(s, i, i + 1, longestBegin, longestEnd);
}
return string(longestBegin, longestEnd);
}
};
P.S. The Solution
class is a requirement of LeetCode.
using std::string;
somewhere, too? \$\endgroup\$using namespace std;
is assumed. \$\endgroup\$