admin管理员组文章数量:1387380
I'm new to Javascript and wrote the code below to determine if a string is a palindrome. I'm curious as to what is the most efficient way to acplish the same task.
var isPalindrome = function (string) {
var leftString = [];
var rightString = [];
// Remove spaces in the string and convert to an array
var strArray = string.split(" ").join("").split("");
var strLength = strArray.length;
// Determine if the string is even or odd in length, then assign left and right strings accordingly
if (strLength % 2 !== 0) {
leftString = strArray.slice(0, (Math.round(strLength / 2) - 1));
rightString = strArray.slice(Math.round(strLength / 2), strLength);
} else {
leftString = strArray.slice(0, (strLength / 2));
rightString = strArray.slice((strLength / 2, strLength))
}
if (leftString.join("") === rightString.reverse().join("")) {
alert(string + " is a palindrome.");
} else {
alert(string + " is not a palindrome.")
}
}
isPalindrome("nurses run");
I'm new to Javascript and wrote the code below to determine if a string is a palindrome. I'm curious as to what is the most efficient way to acplish the same task.
var isPalindrome = function (string) {
var leftString = [];
var rightString = [];
// Remove spaces in the string and convert to an array
var strArray = string.split(" ").join("").split("");
var strLength = strArray.length;
// Determine if the string is even or odd in length, then assign left and right strings accordingly
if (strLength % 2 !== 0) {
leftString = strArray.slice(0, (Math.round(strLength / 2) - 1));
rightString = strArray.slice(Math.round(strLength / 2), strLength);
} else {
leftString = strArray.slice(0, (strLength / 2));
rightString = strArray.slice((strLength / 2, strLength))
}
if (leftString.join("") === rightString.reverse().join("")) {
alert(string + " is a palindrome.");
} else {
alert(string + " is not a palindrome.")
}
}
isPalindrome("nurses run");
Share
Improve this question
asked Feb 3, 2014 at 19:58
Michael DobbertinMichael Dobbertin
771 silver badge6 bronze badges
3
- 2 Firebug has javascript profiling tools. Try a few different approaches and see what performance you get. – GordonM Commented Feb 3, 2014 at 20:00
- If you're concerned with performance, search "jsperf palindrome", which gives you something like this – kalley Commented Feb 3, 2014 at 20:07
- This sounds like homework. :) – reergymerej Commented Feb 3, 2014 at 20:08
6 Answers
Reset to default 3It's not clear if you're talking about efficiency in terms of code length, or amount of putation, but this should be fairly good in both regards. And it takes into account non-alpha characters beside spaces as well as capitalization:
function isPalindrome(str) {
var i, len;
str = str.toLowerCase().replace(/[^a-z]/g, '');
len = str.length;
for(i = 0; i < len / 2; i += 1) {
if(str.charCodeAt(i) != str.charCodeAt(len - i - 1)) {
return false;
}
}
return true;
}
A much shorter approach (though perhaps more putation intensive):
function isPalindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
return str == str.split("").reverse().join("");
}
And if you really want that alert stuff, I'd suggest putting it in a separate function:
function isPalindromeAlert(str) {
alert(str + "is " + (isPalindrome(str) ? "" : "not ") + "a palindrome.");
}
function isPalindrome( s )
{
var i = 0, j = s.length-1;
while( i < j )
if( s[i++].toLowerCase() != s[j--].toLowerCase() ) return false;
return true;
}
I think this one is lot simpler:
var isPalindrome = function (string) {
if (string == string.split('').reverse().join('')) {
alert(string + ' is palindrome.');
}
else {
alert(string + ' is not palindrome.');
}
}
See more: Palindrome check in Javascript
var str = "abcba";
var len = str.Lenght;
var index = 0;
while(index <= len/2 && str[index] == str[len - index - 1]) index++;
if(index == len/2) {
alert(string + " is a palindrome.");
}
else {
alert(string + " is not a palindrome.");
}
You made a few unnecesary operations.
To be efficient, you should avoid unnecessary putations. Ask yourself:
- do you need to remove spaces?
- do you need to convert to an array?
- do you need to allocate new objects for the left and right strings?
- do you need to reverse the string?
The checking can be done in a very simple loop:
var len=string.length;
for (int i=0; i<(len/2); i++) {
if (string[i] != string[len-i-1]) {
alert(string + " is not a palindrome.");
return;
}
}
alert(string + " is a palindrome.");
To ignore spaces and non-alpha numeric characters, it can be re-written as follows:
function isAlphaNumeric( chr ) {
return ( ((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) );
}
// Note - template taken from @Matt's answer!
function isPalindrome( string ) {
var i = 0, j = s.length-1;
while( i < j ) {
if (isAlphaNumeric(string[i])) {
if (isAlphaNumeric(string[j])) {
if ( string[i++].toLowerCase() != string[j--].toLowerCase() )
return false;
} else {
j--;
}
} else {
i++;
if (!isAlphaNumeric(string[j])) j--;
}
}
return true;
}
unreadable + unmaintainable + terse + efficient + recursive + non-branching
function isPalindrome(s,i) {
return (i=i||0)<0|| i>=s.length/2|| s[i]==s[s.length-1-i]&& isPalindrome(s,++i);
}
Fiddle: http://jsfiddle/namcx0yf/
版权声明:本文标题:What's the most efficient way to evaluate if a string is a palindrome using Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744528394a2610883.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论