Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
思路:hashmap存对应char的对应个数。然后检查长度为偶数,不能有奇数个char存在,长度为奇数,只能有一个奇数个存在。
public class Solution { public boolean canPermutePalindrome(String s) { Map<Character,Integer> res=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++) { if(!res.containsKey(s.charAt(i))) { res.put(s.charAt(i),1); } else { res.put(s.charAt(i),res.get(s.charAt(i))+1); } } int odd=0; int l=s.length(); for(int i:res.values()) { if(i%2==1) { odd++; } if(odd==1&&l%2==0) { return false; } if(odd>1) { return false; } } return true; } }
Solution2:
参考了discussion。用array代替hashmap
其实不用考虑偶数长度奇数个char个数为1的情况。如果偶数长度有一个奇数char,那肯定会有另一个奇数char。奇数char的总个数肯定超1。相对的,如果奇数长度只有一个奇数char那就是true,多出来一个那就是false。因此可以合并之前的写法。
public class Solution { public boolean canPermutePalindrome(String s) { int[] htable = new int[256]; for(int i=0; i<s.length(); i++) { htable[s.charAt(i)] += 1; } int count_odd = 0; for(int each : htable){ if(each % 2 == 1) count_odd+=1; if(count_odd > 1) return false; } return true; } }