java/javaAlgorithm

[Leetcode]242. Valid Anagram

rudgh99_algo 2024. 7. 30. 19:59

1. problem : 

https://leetcode.com/problems/valid-anagram/description/

 

2. solution 1 :

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (char c : s.toCharArray()) {
            hashMap.put(c,hashMap.getOrDefault(c,0) + 1);
        }
        for (char c : t.toCharArray()) {
            if (!hashMap.containsKey(c)) {
                return false;
            }
            hashMap.put(c,hashMap.get(c)-1);
            if (hashMap.get(c) == 0) {
                hashMap.remove(c);
            }
        }
        return hashMap.isEmpty();
    }
}

s의 hashMap을 생성한 이후, t의 char가 들어있지 않다면 false를 return. 들어있다면 -1을 한다. 값이 0이라면 제거해 버린다. 마지막으로 hashMap이 비었는지 boolean으로 return. 

 

3. solution 2 :

class Solution {

    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        int[] store = new int[26];

        for (int i = 0; i < s.length(); i++) {
            store[s.charAt(i) - 'a']++;
            store[t.charAt(i) - 'a']--;
        }

        for (int n : store) if (n != 0) return false;

        return true;
    }
}

이 풀이는 'neetcode'한테서 가져왔다. neetcode는 unicode를 이용해서 풀이를 하였다. store라는 배열의 크기를 26개로 만든 이유는 알파벳의 개수가 26개이기 때문이다. 

그런 다음, s.char는 ++해주고 t.char는 --해준다. 이렇게 해서 결과가 다 0으로 구성되어 있다면 anagram에 만족한다.