zoukankan      html  css  js  c++  java
  • 266. Palindrome Permutation

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

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

    这道题收到了Palindrome Permutation2的启发,用了odd检验odd-even>1否。代码如下:

     1 public class Solution {
     2     public boolean canPermutePalindrome(String s) {
     3         Map<Character,Integer> map = new HashMap<>();
     4         int odd = 0;
     5         for(char c:s.toCharArray()){
     6             map.put(c,map.getOrDefault(c,0)+1);
     7             odd+=map.get(c)%2==1?1:-1;
     8         }
     9         return odd>1?false:true;
    10     }
    11 }

    当然,本题也可以不用计数器来做,用hashSet来做,其实说白了,就是看出现奇数的char是否>1,代码如下:

     1 public class Solution {
     2     public boolean canPermutePalindrome(String s) {
     3         Set<Character> set = new HashSet<>();
     4         for(char c:s.toCharArray()){
     5             if(set.contains(c)){
     6                 set.remove(c);
     7             }else{
     8                 set.add(c);
     9             }
    10         }
    11         return set.size()>1?false:true;
    12     }
    13 }
  • 相关阅读:
    imagemagick-图片
    selenium-嘿
    centos命令行连接无线网络
    centos7安装桌面合盖不休眠
    mysql执行命令:ERROR 1820 (HY000): You must reset your password
    编码规范 C++
    Docker使用总结
    JAVA使用总结
    VS IDE 相关
    编程网站总结
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388568.html
Copyright © 2011-2022 走看看