Given a string, determine if a permutation of the string could form a palindrome.code
For example,
"code" -> False, "aab" -> True, "carerac" -> True.orm
判斷是否能夠組成迴文
給一個字符串,判斷字符串中的字符是否能夠組成迴文rem
其實思路都同樣,計算字符串中的字符個數;若字符串的字符有偶數個,則每一個字符的出現次數須要有偶數次;若字符串的字符有奇數個,則最多隻能有一個字符出現過奇數次,其餘字符都須要出現偶數次字符串
public boolean canPermutePalindromeOther1(String s) { Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); } int singleCount = 0; for (Character c : map.keySet()) { if ((map.get(c) & 1) != 0) { singleCount++; } if (singleCount > 1) { break; } } return singleCount <= 1; }
public boolean canPermutePalindromeOther2(String s) { Set<Character> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { if (!set.add(s.charAt(i))) { set.remove(s.charAt(i)); } } return set.size() <= 1; }