Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Friday, February 18, 2011

# Find the Palindromes

[Problem] A palindrome is a string whose reverse is the same as the original. Ignore case, whitespace, and punctuation in the input. If there are more than one palindrome of the maximum length, print the first one. Remove all space and punctuation and convert upper case to lower case in the output. If the input file contains:

Example: From: http://stackoverflow.com/questions/1115001/write-a-function-that-returns-the-longest-palindrome-in-a-given-string
e.g "ccddcc" in the string "abaccddccefe"

Algo :
Steps: Its a brute force method,but it runs in O(n^2) time

Have 2 for loops
for i = 1 to i less than array.length -1
for j=i+1 to j less than array.length
This way you can get substring of every possible combination from the array
Have a palindrome function which checks if a string is palindrome
so for every substring (i,j) call this function, if it is a palindrome store it in a string variable
If you find next palindrome substring and if it is greater than the current one, replace it with current one.
Finally your string variable will have the answer

Purpose: runs better time. If possible O(n) time

Some Links:
http://johanjeuring.blogspot.com/2007/08/finding-palindromes.html
http://stackoverflow.com/questions/2033903/algorithm-to-find-palindromes

Nice Solution in Python:
http://www.akalin.cx/2007/11/28/finding-the-longest-palindromic-substring-in-linear-time/
http://bytes.com/topic/c/answers/692795-test-if-integer-palindrome-c-language

Assume a palindrome in base 10.
sprintf() it to a string, and then check whether the string is palindrome:
len = strlen(str);
for (i = 0; i < len/2; i++) {
if (str[i] != str[len - i - 1])
break; /*it is not palindome*/
}



No comments:

Post a Comment