回文排列。题意是给一个字符串,问这个字符串的任何排列是否能组成一个回文。例子,
Example 1:
Input:"code"
Output: falseExample 2:
Input:"aab"
Output: trueExample 3:
Input:"carerac"
Output: true
思路是遍历input里面的char,用hashset判断,若当前char存在于hashset则减去,若不存在则加入hashset。最后判断hashset的size是否小于等于1。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public boolean canPermutePalindrome(String s) { 3 char[] count = new char[256]; 4 int res = 0; 5 for (char c : s.toCharArray()) { 6 if (count[c] > 0) { 7 count[c]--; 8 } else { 9 count[c]++; 10 } 11 } 12 13 for (int i = 0; i < count.length; i++) { 14 if (count[i] != 0) 15 res++; 16 } 17 return res <= 1; 18 } 19 }
JavaScript实现
1 /** 2 * @param {string} s 3 * @return {boolean} 4 */ 5 var canPermutePalindrome = function (s) { 6 // corner case 7 if (s == null || s.length == 0) return true; 8 9 // normal case 10 let set = new Set(); 11 for (let c of s) { 12 if (set.has(c)) { 13 set.delete(c); 14 } else { 15 set.add(c); 16 } 17 } 18 return set.size <= 1; 19 };