Java, HashMap, O(n) time and O(n) space


  • 3
    J
    public class Solution {
    public boolean isAnagram(String s, String t) {
    	if(s == null && t == null) {
    		return true;
    	}
    	if(s == null || t == null) {
    		return false;
    	}
    	if(s.length() != t.length()) {
    	    return false;
    	}
    	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    	for(int i = 0; i < s.length(); i++) {
    		if(map.containsKey(s.charAt(i))) {
    			map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
    		}
    		else {
    			map.put(s.charAt(i), 1);
    		}
    	}
    	for(int i = 0; i < t.length(); i++) {
    		if(map.containsKey(t.charAt(i))) {
    			map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
    		}
    	}
    	for(int i = 0; i < s.length(); i++) {
    		if(map.get(s.charAt(i)) != 0) {
    			return false;
    		}
    	}
    	return true;
    }
    

    }


  • 0
    K
    public boolean isAnagram(String s, String t) {
        if(s == null && t == null) return true;
        if(s == null || t == null) return false;
        if(s.length() != s.length()) return false;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i = 0; i < s.length(); i++) {
            if(map.containsKey(s.charAt(i))) {
                int value = map.get(s.charAt(i));
                map.put(s.charAt(i), ++value);
            }
            else {
                map.put(s.charAt(i), 1);
            }
        }
        
        for(int j = 0; j < t.length(); j++) {
            if(map.containsKey(t.charAt(j))) {
                int value = map.get(t.charAt(j));
                if(--value == 0) {
                    map.remove(t.charAt(j));
                }
                else {
                    map.put(t.charAt(j), value);
                }
            }
            else
                return false;
        }
        
        if(map.isEmpty()) return true;
        else return false;
    }

Log in to reply
 

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