Javascript String is palindrome after rearranging

Description

Javascript String is palindrome after rearranging

// given a ramdom string of letters, return true if the letters
// can be rearranged to form a palindrome, otherwise, return false

// Ex1.//from   w w w . ja v a 2 s.  c o  m
// Input: pacescaps
// Output: true

// Ex2.
// Input: javascript
// Output: false

/**
  * @function anagramPalindrome
  * @param {string} str
  * @return {boolean}
  */

function anagramPalindrome(str) {
  var letters = {};
    var oddCount = 0;

    for (var i=0; i < str.length; i++) {
        var curr = str.charAt(i);
        if (!(curr in letters)) {
            letters[curr] = 0;
        }
        
        if (letters[curr] > 0) {
            letters[curr]--;
            oddCount--;
        } else {
            letters[curr]++;
            oddCount++;
        }
    }

    if (oddCount <= 1) {
        return true;
    } else {
        return false;
    }
}

console.log(anagramPalindrome('armdabbmaboobrd')); // bombard a drab mob => true
console.log(anagramPalindrome('armdabsbmaboobrd')); // bombards a drab mob => false
console.log(anagramPalindrome('tdolgsaetagdliadaoasaasinvdeavn')); // a santa dog lived as a devil god at nasa => true
console.log(anagramPalindrome('raoistddtagstonveakaaeawfewosln')); // a santa dog lived at nasa for two weeks => false
  



PreviousNext

Related