i have the following:
function checkPalindrom(palindrom)
{
for( var i = palindrom.length; i > 0; i-- )
{
if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
{
document.write('the word is palindrome.');
}else{
document.write('the word is not palindrome!');
}
}
}
checkPalindrom('wordthatwillbechecked');
What is wrong with my code? i want to check if the word is palindrome.
As a much clearer recursive function: http://jsfiddle.net/dmz2x117/
I thought I'd share my own solution:
Hope will help someone.
I found this on an interview site:
Playing around with it I came up with this ugly piece of code :)
Just leaving it here for posterity.
Sharing my fast variant which also support spaces
The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.
Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume
false
and alter the logic if its looking to betrue
.isPalindrome()
:Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to
break
/return
once they meet in the middle, but it may save some work to only give each iterator a half-length by default.for
loops seem to force the use of more checks, so I usedwhile
loops - which I'm less comfortable with.Here's the code:
Notice that if the loops count out, it returns
true
. All the logic should be inverted so that it by default returnsfalse
. I also used one short cut methodString.prototype.charAt(n)
, but I felt OK with this as every language natively supports this method.First problem
= is assign == is compare
Second problem, Your logic here is wrong
You are subtracting one from the charAt and not the length.
Third problem, it still will be wrong since you are not reducing the length by i.