标签:
题目:
Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
Hint:
链接: http://leetcode.com/problems/palindrome-permutation/
题解:
判断一个String是否可以组成一个Palindrome。我们只需要计算单个字符的个数就可以了,0个或者1个都是可以的,超过1个则必不能成为Palindrome。双数的字符我们可以用Set来even out。
Time Complexity - O(n), Space Complexity - O(n)
public class Solution { public boolean canPermutePalindrome(String s) { if(s == null) { return false; } Set<Character> set = new HashSet<>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(set.contains(c)) { set.remove(c); } else { set.add(c); } } return set.size() <= 1; } }
Reference:
https://leetcode.com/discuss/71076/5-lines-simple-java-solution-with-explanation
https://leetcode.com/discuss/70848/3-line-java-functional-declarative-solution
https://leetcode.com/discuss/53180/1-4-lines-python-ruby-c-c-java
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5021398.html