Java HashTable solution


  • 1
    Q
    public class Solution {
        public boolean canPermutePalindrome(String s) {
            Map<Character, Integer> map = new HashMap();
            for(char c : s.toCharArray()){
                if(map.containsKey(c)) map.remove(c);
                else map.put(c, 1);
            }
            if(map.size() > 1) return false;
            else return true;
        }
    }
    

  • 1
    R

    you could use a Set instead of a map, In map you are just storing extra value, but not sure if that makes much of a difference.

    Here is the code with HashSet.

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

  • 0
    A
    This post is deleted!

Log in to reply
 

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