Mercurial > algorithms
changeset 7:e1578d3eee36
Added is_palindrome tests.
author | Eris Caffee <discordia@eldalin.com> |
---|---|
date | Tue, 05 May 2015 12:02:16 -0500 |
parents | 9e16e99a4a10 |
children | 707cbc379d26 |
files | palindrome/is_palindrome.cpp palindrome/is_palindrome.pl |
diffstat | 2 files changed, 65 insertions(+), 0 deletions(-) [+] |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/palindrome/is_palindrome.cpp Tue May 05 12:02:16 2015 -0500 1.3 @@ -0,0 +1,34 @@ 1.4 +#include <cstring> 1.5 +#include <cctype> 1.6 +#include <iostream> 1.7 +#include <string> 1.8 + 1.9 +bool is_palindrome( const char *s ) { 1.10 + const char * first = s; 1.11 + const char * last = s + strlen(s) - 1; 1.12 + while ( first < last ) { 1.13 + while ( ! isalpha( *first ) && *first != 0 ) 1.14 + first++; 1.15 + while ( ! isalpha( *last ) && last >= s ) 1.16 + last--; 1.17 + if ( toupper( *first ) != toupper( *last ) ) { 1.18 + return false; 1.19 + } 1.20 + first++; 1.21 + last--; 1.22 + } 1.23 + return true; 1.24 + } 1.25 + 1.26 +bool is_palindrome( std::string s ) { 1.27 + return is_palindrome( s.c_str() ); 1.28 + } 1.29 + 1.30 +int main ( int argc, char **argv ) { 1.31 + for ( int i = 1; i < argc; ++i ) { 1.32 + std::string s(argv[1]); 1.33 + std::cout << is_palindrome( s ) << std::endl; 1.34 + } 1.35 + 1.36 + return 0; 1.37 + }
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 2.2 +++ b/palindrome/is_palindrome.pl Tue May 05 12:02:16 2015 -0500 2.3 @@ -0,0 +1,31 @@ 2.4 +use strict; 2.5 +use warnings; 2.6 + 2.7 +# This implements the same algorithm as the C++ version, but it has to first 2.8 +# split the string into an array, and therefore uses O(N) extra space. 2.9 + 2.10 +sub is_palindrome { 2.11 + my $s = shift; 2.12 + my @chars = split( //, $s ); 2.13 + my $first = 0; 2.14 + my $last = scalar( @chars ) - 1; 2.15 + while ( $first < $last ) { 2.16 + while ( ( $chars[$first] !~ /^[a-zA-Z]$/ ) and ( $first < scalar( @chars ) ) ) { 2.17 + $first++; 2.18 + } 2.19 + while ( ( $chars[$last] !~ /^[a-zA-Z]$/ ) and ( $last > 0 ) ) { 2.20 + $last--; 2.21 + } 2.22 + 2.23 + if ( lc($chars[$first]) ne lc($chars[$last]) ) { 2.24 + return 0; 2.25 + } 2.26 + $first++; 2.27 + $last--; 2.28 + } 2.29 + return 1; 2.30 +} 2.31 + 2.32 +for ( my $i = 0; $i < scalar( @ARGV ) ; $i++ ) { 2.33 + print is_palindrome( $ARGV[$i] ) . "\n"; 2.34 +}