Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
这道题收到了Palindrome Permutation2的启发,用了odd检验odd-even>1否。代码如下:
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 Map<Character,Integer> map = new HashMap<>(); 4 int odd = 0; 5 for(char c:s.toCharArray()){ 6 map.put(c,map.getOrDefault(c,0)+1); 7 odd+=map.get(c)%2==1?1:-1; 8 } 9 return odd>1?false:true; 10 } 11 }
当然,本题也可以不用计数器来做,用hashSet来做,其实说白了,就是看出现奇数的char是否>1,代码如下:
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 Set<Character> set = new HashSet<>(); 4 for(char c:s.toCharArray()){ 5 if(set.contains(c)){ 6 set.remove(c); 7 }else{ 8 set.add(c); 9 } 10 } 11 return set.size()>1?false:true; 12 } 13 }