Simple Java Solution


  • 3
    S
       HashMap<Character,Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++){
            if (map.containsKey(s.charAt(i))){
                map.remove(s.charAt(i));
            }else{
                map.put(s.charAt(i), 1);
            }
        }
        if (map.size() > 1) return false;
        else return true;

  • 0
    A

    Or we only need a HashSet instead of HashMap, no need for the value 1 from key-value pair:

    public class Solution {
        public boolean canPermutePalindrome(String s) {
            if (s == null || s.length() == 0) {
                return false;
            }
            HashSet<Character> set = new HashSet<Character>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (set.contains(c)) {
                    set.remove(c);
                } else {
                    set.add(c);
                }
            }
            return set.size() <= 1;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.