Amazon Interview Question
Software Engineer in TestsTo explicitly satisfy such condition, you don't need to first go through whole string to find out end of string.
Following code is good enough:
===============================
bool isPalindrome(char * str)
{
assert(str != 0);
int i=0, j = strlen(str)-1;
while(i<j)
{
if(str[i] == " ")
{
i++;
}
else if(str[j] == " ")
{
j--;
}
else if(str[i] != str[j])
{
return false;
}
else
{
i++; j--;
}
}
return true;
}
String str = "abcfba";
Boolean palindrome=true;
if(str.length()==0 | str.length()==1)
{
palindrome=true;
}
else
{
int i=0;
int j=str.length();
for(i=0;i<str.length();i++)
{
for(j=str.length()-1;j>0;j--)
{
if(str.charAt(i)==str.charAt(j))
{
palindrome = true;
}
else
{
palindrome = false;
}
}
}
I think the running time is O(n^2)..Is there anything better than this one?
I think the qtn is not to find a string is palindrome or not?
Algorithm to find that palindrome can be made from a string
eg:
damam >> madam
I would write an algorithm like this
scan each chars and store in a int array[256] their counts
check for the count of each chars.
if there are more than one odd count it cannot make a palindrome.
For a string to become palindrome there are two cases:
1) if the length of the string is Odd. In this case we will have all the charaters even numbers of time except for one character.
2) if the length of the String is Even. here all the characters should occur even numbers of time.
So, we maintain a HashMap<Character,Integer> of the String
we iterate throught the map
and every entry in the map we check the value
if the length is even
if at anytime we found any key with value which is odd then return false(No Palindrome possible)
else if every key has even value then return true(palindrome is possible)
if the length is odd
if key has even value; continue;
if key has odd value keep a counter and increment its value for every odd value of a key.
if the counter!=1 return false;
else return true;
That is true anon! we can try this!! since spaces affect the result
how ever, we can consider a lot of special cases such as:
upper and lower case
dots, commas, and stuff like that
spaces
and so on:
Example:
A dog! A panic in a pagoda!
Ah, Satan sees Natasha.
Are we not drawn onward, we few, drawn onward to new era?
Do geese see God?
I prefer pi.
If I had a hi-fi.
Ma is as selfless as I am.
Mr. Owl ate my metal worm.
Never odd or even.
No devil lived on.
No lemon, no melon.
No, sir, away! A papaya war is on!
Red rum, sir, is murder.
Rise to vote, sir.
So many dynamos!
this code just check for spaces. I do not consider upper cases, and special characters. but I don't think it is hard to implement it mbut in an interview you have to let the interviewer know that you notice that.
axel_net@hotmail.com
- Axel David Velazquez Huerta. October 18, 2009