# HG changeset patch # User Eris Caffee # Date 1430845336 18000 # Node ID e1578d3eee360b80fed2fb5113befea56d305b9a # Parent 9e16e99a4a10840effaa3f81df3c0e0e8cf3dce1 Added is_palindrome tests. diff -r 9e16e99a4a10 -r e1578d3eee36 palindrome/is_palindrome.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/palindrome/is_palindrome.cpp Tue May 05 12:02:16 2015 -0500 @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +bool is_palindrome( const char *s ) { + const char * first = s; + const char * last = s + strlen(s) - 1; + while ( first < last ) { + while ( ! isalpha( *first ) && *first != 0 ) + first++; + while ( ! isalpha( *last ) && last >= s ) + last--; + if ( toupper( *first ) != toupper( *last ) ) { + return false; + } + first++; + last--; + } + return true; + } + +bool is_palindrome( std::string s ) { + return is_palindrome( s.c_str() ); + } + +int main ( int argc, char **argv ) { + for ( int i = 1; i < argc; ++i ) { + std::string s(argv[1]); + std::cout << is_palindrome( s ) << std::endl; + } + + return 0; + } diff -r 9e16e99a4a10 -r e1578d3eee36 palindrome/is_palindrome.pl --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/palindrome/is_palindrome.pl Tue May 05 12:02:16 2015 -0500 @@ -0,0 +1,31 @@ +use strict; +use warnings; + +# This implements the same algorithm as the C++ version, but it has to first +# split the string into an array, and therefore uses O(N) extra space. + +sub is_palindrome { + my $s = shift; + my @chars = split( //, $s ); + my $first = 0; + my $last = scalar( @chars ) - 1; + while ( $first < $last ) { + while ( ( $chars[$first] !~ /^[a-zA-Z]$/ ) and ( $first < scalar( @chars ) ) ) { + $first++; + } + while ( ( $chars[$last] !~ /^[a-zA-Z]$/ ) and ( $last > 0 ) ) { + $last--; + } + + if ( lc($chars[$first]) ne lc($chars[$last]) ) { + return 0; + } + $first++; + $last--; + } + return 1; +} + +for ( my $i = 0; $i < scalar( @ARGV ) ; $i++ ) { + print is_palindrome( $ARGV[$i] ) . "\n"; +}