/** * @param {string}s * @return {boolean} */ var canPermutePalindrome = function (s) { s = s.split("").sort(); for (let i = 0; i < s.length - 1; i++) { if (s[i] === s[i + 1]) { s.splice(i, 2); i -= 2; } } return s.length <= 1; };
哈希表
1 2 3 4 5 6 7 8 9
/** * @param {string}s * @return {boolean} */ var canPermutePalindrome = function (s) { const map = newMap(); for (const arr of s) map.set(arr, map.has(arr) ? map.get(arr) + 1 : 1); return [...map.values()].filter((e) => e % 2 !== 0).length <= 1; };
哈希表优化
1 2 3 4 5 6 7 8 9 10 11 12
/** * @param {string}s * @return {boolean} */ var canPermutePalindrome = function (s) { const map = {}; for (const arr of s) { if (map[arr]) delete map[arr]; else map[arr] = true; } returnObject.keys(map).length <= 1; };
set
1 2 3 4 5 6 7 8
var canPermutePalindrome = function (s) { const set = newSet(); for (const arr of s) { if (set.has(arr)) set.delete(arr); else set.add(arr); } return set.size <= 1; };