• Leetcode Palindrome Permutation


    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?

    解题思路:

    permutation 排列, palindrome 回文 判断一个string 能否组合成一个回文。思路参考Hint.

    我用了HashMap, 计算如果character 的数目是odd, 最多只有一个时,为真。但从discussion中发现,有人的方法更巧妙,复杂度更低。贴过来参考。

    还有一种方法,用HashSet.


     Java code:

    my code:(use map)

    public boolean canPermutePalindrome(String s) {
            Map<Character, Integer> x = new HashMap<Character, Integer>();
            for(int i = 0; i< s.length(); i++){
                if(x.containsKey(s.charAt(i))){
                    x.put(s.charAt(i), x.get(s.charAt(i))+1);
                }else{
                    x.put(s.charAt(i), 1);
                }
            }
            int odd = 0;
            for(Character key: x.keySet()){
                int number = x.get(key);
                if(number % 2 == 1) {
                    odd++;
                }
            }
            if(odd == 0 || odd == 1){
                return true;
            }
            return false;
        }

    better code:(use map)

    public boolean canPermutePalindrome(String s) {
            Map<Character, Integer> x = new HashMap<Character, Integer>();
            for(int i = 0; i< s.length(); i++){
                if(x.containsKey(s.charAt(i))){
                    x.remove(s.charAt(i));
                }else{
                    x.put(s.charAt(i), 1);
                }
            }
            if(x.size() > 1) {
                return false;
            }
            return true;
        }

    better code: (use set)

    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.remove(s.charAt(i));
                }else {
                    set.add(s.charAt(i));
                }
            }
            if(set.size() == 0 || set.size() == 1){
                return true;
            }
            return false;
        }

    Reference:

    1. https://leetcode.com/discuss/53295/java-solution-w-set-one-pass-without-counters

    2. https://leetcode.com/discuss/53472/simple-java-solution

     

  • 相关阅读:
    radioButton
    事件分发
    自定义属性
    自定义View
    拦截来电
    Messenger信使
    使用AIDL远程调用服务中的方法
    利用接口调用服务中特定的方法
    Service服务
    BroadcastReceiver广播接受者
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4831003.html
Copyright © 2020-2023  润新知