zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    Ajax
    PS将图标变灰
    圆角
    前端性能优化最佳实践(转)
    jquery $(document).ready() 与window.onload的区别
    js阻止冒泡及jquery阻止事件冒泡示例介绍
    CSS选择器、CSS hack及CSS执行效率
    Github快速入门手册
    Windows 系统下Git安装图解
    史上最全github使用方法:github入门到精通
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4831003.html
Copyright © 2011-2022 走看看