码迷,mamicode.com
首页 > 其他好文 > 详细

266. Palindrome Permutation

时间:2015-12-05 14:15:01      阅读:122      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!