Given a string, determine if a permutation of the string could form a palindrome.
For example,"code" -> False, "aab" -> True, "carerac" -> True.
解法一:
解题思路:
The idea is to iterate over string, adding current character to set if set doesn't contain that character, or removing current character from set if set contains it. When the iteration is finished, just return set.size()==0 || set.size()==1.
set.size()==0 corresponds to the situation when there are even number of any character in the string, and set.size()==1 corresponsds to the fact that there are even number of any character except one.
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 Set<Character> set=new HashSet<Character>(); 4 for(int i=0; i<s.length(); ++i){ 5 if (!set.contains(s.charAt(i))) 6 set.add(s.charAt(i)); 7 else 8 set.remove(s.charAt(i)); 9 } 10 return set.size()==0 || set.size()==1; 11 } 12 }reference: https://leetcode.com/discuss/53295/java-solution-w-set-one-pass-without-counters
转载于:https://www.cnblogs.com/hygeia/p/5062925.html
相关资源:JAVA上百实例源码以及开源项目