Valid Anagram: Keeping count with constant access time

Jay·2022년 5월 16일
0

Grind 120

목록 보기
7/38

First Thoughts: anagram checkable by comparing the intersections of the two char arrays. 문제점: 서로 체크하는지 확인해야되기 때문에 두 번 체크해야 한다. 따라서 문자와 그의 frequency count를 저장하는 hashmap을 생성하고 마지막에 두 map 이 같은지 확인만 하면 가능.

My Solution:

class Solution {
    public boolean isAnagram(String s, String t) {
        boolean result = true;
        HashMap<Character, Integer> smap = new HashMap<>();
        HashMap<Character, Integer> tmap = new HashMap<>();
        for (char c : s.toCharArray()) {
            smap.putIfAbsent(c, 0);
            smap.put(c, smap.get(c)+1);
        }
        for (char c : t.toCharArray()) {
            tmap.putIfAbsent(c, 0);
            tmap.put(c, tmap.get(c)+1);
        }
        return smap.equals(tmap);
    }
}

Improved Solution: keeping one counter array (adding char count for s, subtracting count for t)

if (s.length()!=t.length()) return false;
int arr[] = new int[26];
for (char c : s.toCharArray()) arr[(int) c - 'a']++
for (char c : t.toCharArray()) {
	arr[(int) c - 'a']--;
    if (arr[(int) c - 'a'] < 0) return false;
}
return true;

Catch Point:

  1. s equates to addition counter process, t equivalent to subtraction counter process
  2. can check if two map collection is equal to another by using .equals (rather than iterating through all the keys and values of both collections), much simpler and avoids unnecessary complications

0개의 댓글