Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Palindrome using iterators #196

Merged
merged 2 commits into from
Oct 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions classicalAlgos/checkPalindrome/palindrome_WithIterators.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <iostream>
#include <string>

/**
* Function to check if a string is palindrome.
* @param s string to check.
* @return true if the string is palindrome; false otherwise.
*/
bool checkPalindrome(std::string s) {
auto front = s.cbegin(); // const_iterator pointing to the first character of the string
auto back = s.cend() - 1; // const_iterator pointing to the last valid character of the string

// every time front moves forward, back moves back, both towards the center
while(front != back) { // compare front and back
if(*front != *back) { return false; }
front++;
back--;
}

return true;
}

/**
* Driver code.
*/
int main() {
std::string s;
std::cin >> s;

if(checkPalindrome(s)) { std::cout << "Palindrome" << std::endl; }
else { std::cout << "Not Palindrome" << std::endl; }

return 0;
}