Two solutions sharing same idea, different time complexity


  • 0
    	/**
    	 * 38ms
    	 */
    	public boolean isAnagramV1(String s, String t) {
    		Map<Character, Integer> charCount = new HashMap<Character, Integer>();
    		for (char c : s.toCharArray())
    			charCount.put(c, charCount.getOrDefault(c, 0) + 1);
    		for (char c : t.toCharArray())
    			charCount.put(c, charCount.getOrDefault(c, 0) - 1);
    		for (int count : charCount.values())
    			if (count != 0)
    				return false;
    		return true;
    	}
    
    	/**
    	 * 4ms
    	 */
    	public boolean isAnagramV2(String s, String t) {
    		int[] charCount = new int[26];
    		Arrays.fill(charCount, 0);
    
    		for (char c : s.toCharArray())
    			charCount[c - 'a']++;
    		for (char c : t.toCharArray())
    			charCount[c - 'a']--;
    		for (int num : charCount)
    			if (num != 0)
    				return false;
    		return true;
    	}
    

Log in to reply
 

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