Java - Use map, one scan


  • 0
    J
    public class Solution {
    public boolean canPermutePalindrome(String s) {
    	if (s == null || s.isEmpty())
    		return true;
    	Map<Character, Integer> freq = new HashMap<>();
    	for (char c : s.toCharArray()) {
    		if (freq.containsKey(c)) {
    			freq.put(c, freq.get(c) + 1);
    		} else {
    			freq.put(c, 1);
    		}
    	}
    	int oddCount = 0;
    	for (Integer i : freq.values()) {
    		if ((i.intValue() % 2) > 0) {
    			oddCount++;
    			if (oddCount > 1)
    				return false;
    		}
    	}
    	return true;
    }
    

    }


  • 0

    Using freq.getOrDefault could save you five lines.


  • 0
    J

    ah...., that is in Java 8, I am still using Java 7 in my Eclipse. Guess I need an upgrade. thanks!


  • 0
    J
    public class Solution {
    public boolean canPermutePalindrome(String s) {
    	if (s == null || s.isEmpty())
    		return true;
    	Map<Character, Integer> freq = new HashMap<>();
    	for (char c : s.toCharArray()) {
    		freq.put(c, freq.getOrDefault(c, 0) + 1);
    	}
    	int oddCount = 0;
    	for (Integer i : freq.values()) {
    		if ((i.intValue() % 2) > 0) {
    			oddCount++;
    			if (oddCount > 1)
    				return false;
    		}
    	}
    	return true;
    }
    

    }


Log in to reply
 

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