首页 > 其他 > 详细

266. Palindrome Permutation - Easy

时间:2018-12-26 16:19:32      阅读:120      评论:0      收藏:0      [点我收藏+]

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

 

扫一遍s,统计频率,奇数频率最多只能出现一次。用cnt表示结果,cnt += map[i]的频率%2,如果cnt > 1,则不可能是回文

time: O(n), space: O(n)

class Solution {
    public boolean canPermutePalindrome(String s) {
        HashMap<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 cnt = 0;
        for(Map.Entry<Character, Integer> entry : map.entrySet()) {
            cnt += entry.getValue() % 2;
        }
        return cnt <= 1;
    }
}

 

266. Palindrome Permutation - Easy

原文:https://www.cnblogs.com/fatttcat/p/10179670.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!