Skip to content

Instantly share code, notes, and snippets.

@fpelliccioni
Created July 9, 2018 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpelliccioni/a1fea94d92a8c16ca4c8e61ceb68b7ec to your computer and use it in GitHub Desktop.
Save fpelliccioni/a1fea94d92a8c16ca4c8e61ceb68b7ec to your computer and use it in GitHub Desktop.
C++17 + Concepts: Palindrome check for Forward Iterators
//Complexity:
// Time: floor(n / 2) equality comparisons
// Space: floor(n / 2) recursive calls
template <ForwardIterator I>
requires(Readable<I>)
std::pair<bool, I> palindrome_recursive(I f, DistanceType<I> n) {
//precondition: readable_weak_range(f, n)
if (zero(n)) return {true, f};
if (one(n)) return {true, ++f};
auto r = palindrome_recursive(std::next(f), n - 2);
if ( ! r.first) return r;
if (*f != *r.second) return {false, r.second};
return {true, ++r.second};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment