• [LeetCode] 266. Palindrome Permutation


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

    Example 1:

    Input: "code"
    Output: false

    Example 2:

    Input: "aab"
    Output: true

    Example 3:

    Input: "carerac"
    Output: true

    回文排列。

    题意是给一个字符串,问这个字符串的任何排列是否能组成一个回文。

    思路是遍历 input 里面的 char,用 hashset 判断,若当前 char 存在于 hashset 则减去,若不存在则加入 hashset。最后判断 hashset 的 size 是否小于等于1。这里的逻辑是,如果这个单词的某个字母组合能构成回文,那么这些字母里面至多只有一个字母的出现次数是奇数,其他的字母的出现次数一定是偶数。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean canPermutePalindrome(String s) {
     3         char[] count = new char[256];
     4         int res = 0;
     5         for (char c : s.toCharArray()) {
     6             if (count[c] > 0) {
     7                 count[c]--;
     8             } else {
     9                 count[c]++;
    10             }
    11         }
    12 
    13         for (int i = 0; i < count.length; i++) {
    14             if (count[i] != 0)
    15                 res++;
    16         }
    17         return res <= 1;
    18     }
    19 }

    JavaScript实现

     1 /**
     2  * @param {string} s
     3  * @return {boolean}
     4  */
     5 var canPermutePalindrome = function (s) {
     6     // corner case
     7     if (s == null || s.length == 0) return true;
     8 
     9     // normal case
    10     let set = new Set();
    11     for (let c of s) {
    12         if (set.has(c)) {
    13             set.delete(c);
    14         } else {
    15             set.add(c);
    16         }
    17     }
    18     return set.size <= 1;
    19 };

    LeetCode 题目总结

  • 相关阅读:
    CSS3 Media Queries 片段
    针对移动设备的CSS3布局
    移动Web界面样式-CSS3
    em与px区别-CSS教程
    webApp添加到iOS桌面
    字典(dick)
    元组(Tuple)
    列表(list)
    字符串的常用方法
    运算符
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12521841.html
Copyright © 2020-2023  润新知