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

    解析

    判断是否可以组成回文
    给一个字符串,判断字符串中的字符是否可以组成回文

    思路

    其实思路都一样,计算字符串中的字符个数;若字符串的字符有偶数个,则每个字符的出现次数需要有偶数次;若字符串的字符有奇数个,则最多只能有一个字符出现过奇数次,其他字符都需要出现偶数次

    解法1:利用Map 的key的唯一性

    public boolean canPermutePalindromeOther1(String s) {
            Map<Character, Integer> map = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
            }
            int singleCount = 0;
            for (Character c : map.keySet()) {
                if ((map.get(c) & 1) != 0) {
                    singleCount++;
                }
                if (singleCount > 1) {
                    break;
                }
            }
            return singleCount <= 1;
        }
    

    解法2:利用Set元素的唯一性

    public boolean canPermutePalindromeOther2(String s) {
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < s.length(); i++) {
                if (!set.add(s.charAt(i))) {
                    set.remove(s.charAt(i));
                }
            }
            return set.size() <= 1;
        }
    
  • 相关阅读:
    反爬的几种手段总结
    算法基础篇一
    python总结九
    python总结八
    python总结七
    python总结六
    初识Machine学习
    python总结五
    python总结四
    python总结三
  • 原文地址:https://www.cnblogs.com/shanelau/p/7240569.html
Copyright © 2011-2022 走看看