Friday, May 9, 2008

Palindromes - Solution

There are multiple ways to solve this trivial problem.
For a beginner, there is one catch in this problem. How to make it case insensitive? Basically, we can do so by changing the string to all upper or all lowercase letters and then check for palindromes.

There maybe any number of ways to approach this problem. I'll list down the 2 ways that usually people apply.

1. Reverse the string and check if the strings are the same



There are quite a few things to learn here.
i> There are library functions available to check if a character is uppercase or lowercase. There are also functions to convert a character from uppercase to lowercase and visa-versa. You can find these functions is ctype.h header file.
ii> Note that we did not compare the reverse of the string with str using the '==' operator. Can you guess why? Basically, because the '==' operator returns true only if the two strings share the same memory location. So we use the 'compare' method in the 'string' class.


2. Compare the 1st against the last character, 2nd against the 2nd last character and so on till we reach the middle.
This one is simple. Here is the code.



Click on the images for code clarity.

Problem 9 - Palindromes

Write a program to find if a string is a palindrome.
Make it case insensitive.

Eg. "MADAM" - returns true
"ROB" - returns false
"Madam" - returns true
"mADaM" - returns true
"WhaWha"- returns false

Day 8 - Solution

The first way is to go by a Brute Force string matching technique.
I guess its useless to give the algorithm if you are giving the source code anyways.

So here is the program.



Now lets try to do the same using the built in features of the 'string' class. Remember, our strings are not (char *) any more, they are objects of the 'string' class. Check out how our whole function that we wrote above, is replaced with a single statement.

Prog:



Note: Click on the image for clarity in reading.