How to write palindrome in JavaScript

前端 未结 30 1671
情书的邮戳
情书的邮戳 2020-11-29 02:42

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad

相关标签:
30条回答
  • 2020-11-29 03:40

    Here's a one-liner without using String.reverse,

    const isPal = str => Array
      .apply(null, new Array(strLen = str.length))
      .reduce((acc, s, i) => acc + str[strLen - (i + 1)], '') === str;
    
    0 讨论(0)
  • 2020-11-29 03:42

    str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.

    function palindrome(str) {
    
      var str1 = str.toLowerCase().replace(/\s/g, '').replace(
        /[^a-zA-Z 0-9]/gi, "");
    
      var str2 = str.toLowerCase().replace(/\s/g, '').replace(
        /[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");
    
    
      if (str1 === str2) {
        return true;
      }
      return false;
    }
    
    palindrome("almostomla");
    
    0 讨论(0)
  • 2020-11-29 03:44

    Use something like this

    function isPalindrome(s) {
        return s == s.split("").reverse().join("") ? true : false;
    }
    
    alert(isPalindrome("noon"));
    

    alternatively the above code can be optimized as [updated after rightfold's comment]

    function isPalindrome(s) {
        return s == s.split("").reverse().join("");
    }
    
    alert(isPalindrome("malayalam")); 
    alert(isPalindrome("english")); 
    
    0 讨论(0)
  • 2020-11-29 03:44

    Taking a stab at this. Kind of hard to measure performance, though.

    function palin(word) {
        var i = 0,
            len = word.length - 1,
            max = word.length / 2 | 0;
    
        while (i < max) {
            if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
                return false;
            }
            i += 1;
        }
        return true;
    }
    

    My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.

    0 讨论(0)
  • 2020-11-29 03:44

    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 be true.

    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 used while loops - which I'm less comfortable with.

    Here's the code:

    /**
     * TODO: If func counts out, let it return 0
     *  * Assume !isPalindrome (invert logic)
     */
    function isPalindrome(S){
        var s = S
          , len = s.length
          , mid = len/2;
          , i = 0, j = len-1;
    
        while(i<mid){
            var l = s.charAt(i);
            while(j>=mid){
                var r = s.charAt(j);
                if(l === r){
                    console.log('@while *', i, l, '...', j, r);
                    --j;
                    break;
                }
                console.log('@while !', i, l, '...', j, r);
                return 0;
            }
            ++i;
        }
        return 1;
    }
    
    var nooe = solution('neveroddoreven');  // even char length
    var kayak = solution('kayak');  // odd char length
    var kayaks = solution('kayaks');
    
    console.log('@isPalindrome', nooe, kayak, kayaks);
    

    Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.

    0 讨论(0)
  • 2020-11-29 03:44

    Here's another way of doing it:

    function isPalin(str) {
      str = str.replace(/\W/g,'').toLowerCase();
      return(str==str.split('').reverse().join(''));
    }
    
    0 讨论(0)
提交回复
热议问题