首页 > 其他 > 详细

266. Palindrome Permutation

时间:2015-12-05 14:14:03      阅读:156      评论:0      收藏:0      [点我收藏+]

题目:

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code" -> False, "aab" -> True, "carerac" -> True.

Hint:

    1. Consider the palindromes of odd vs even length. What difference do you notice?
    2. Count the frequency of each character.
    3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

链接: 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

266. Palindrome Permutation

原文:http://www.cnblogs.com/yrbbest/p/5021398.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!