Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False, "aab"
-> True, "carerac"
-> True.
这种题目很多方法,写了以下三种:
- 用一个set,放入char,重复(放不进去)拿出来,最后确认size,0或者1则是true,否则false
- 用一个boolean和hashset去跟踪
- 用一个array of int,放入,重复则index –,最后判断index的数字
public class Solution { public boolean canPermutePalindrome(String s) { Set<Character> set=new HashSet<Character>(); for(int i=0; i<s.length(); ++i){ if (!set.contains(s.charAt(i))) set.add(s.charAt(i)); else set.remove(s.charAt(i)); } return set.size()==0 || set.size()==1; } }
public class Solution { public boolean canPermutePalindrome(String s) { HashMap<Character,Integer> map = new HashMap<>(); boolean res = false; for(int i=0;i<s.length();i++){ if(map.get(s.charAt(i)) == null){ map.put(s.charAt(i), 1); res = !res; } else{ if(map.get(s.charAt(i)) == 0){ map.put(s.charAt(i), 1); res = !res; } else{ map.put(s.charAt(i), 0); res = !res; } } System.out.println("s:"+i+"res:"+res); } return res; } }
public class Solution { public boolean canPermutePalindrome(String s) { int[] check = new int[128]; int index = s.length(); for(int i=0;i<s.length();i++){ if(check[s.charAt(i) - 'a'] == 1){ check[s.charAt(i) - 'a'] =0; index = index -2; } else{ check[s.charAt(i) - 'a'] = 1; } } if(index ==1 || index == 0){ return true; } return false; } }