Created
July 9, 2018 01:58
-
-
Save fpelliccioni/a1fea94d92a8c16ca4c8e61ceb68b7ec to your computer and use it in GitHub Desktop.
C++17 + Concepts: Palindrome check for Forward Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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