bool isPalindrome( string s )
{
bool result = true;
size_t begin = 0;
size_t end = s.size( ) - 1;
while( begin != end )
{
if (s[begin] != s[end] )
{
result = false;
break;
}
begin++; end--;
}
return( result );
}
This code is on a practice test. Apparently, it will run, but there is a certain bug with it. What would be the fix to fix this bug?
bool palindrome( std::string s )
{
// the string may be empty; we need to take care of that
if( s.size() < 2 ) returntrue ; // *** added: either empty or contains just one character
// rest of the code
}
begin may never be equal to end. Consider strings of even length. e.g.
(begin,end) = (0,3) -> (1,2) -> (2,1) -> (3,0) -> trouble
Change while( begin != end )
to while( begin < end )
This could also remove the necessity of testing separately for empty strings (provided you make begin and end into int, so that end can hold a negative).