Valid Anagram

초보개발·2023년 8월 29일
0

leetcode

목록 보기
20/39

문제

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

풀이

  • 아나그램: 문자열 t를 재배치하여 만든 문자열 s
    • "anagram", "nagaram"은 아나그램
    • "rat", "car"는 아나그램이 아님
  • 아나그램이라는 것은 즉, s의 각 문자의 개수와 t의 각 문자의 개수가 일치하는지 확인하는 것이다.
  • Counter를 사용하여 객체가 일치하는지 확인하면 된다.

수도 코드

s_counter = Counter(s)
t_counter = Counter(t)
return s_counter == t_counter # return boolean type

Solution Python(Runtime: 32ms)

from collections import Counter

class Solution(object):
    def isAnagram(self, s, t):
        return Counter(s) == Counter(t)

Solution Java(Runtime: 5ms)

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] arr = new int[26];

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

        for(int i = 0; i < 26; i++) {
            if (arr[i] < 0) {
                return false;
            }
        }
        return true;
    }
}

파이썬은 Counter를 사용하여 간단하게 카운트하였고, Java는 a ~ z까지의 개수를 담는 배열을 생성하여 s, t의 문자 개수를 저장하도록 했다. 만약 배열의 값이 0 미만이라면 아나그램이 아니므로 false를 리턴하였다.

다른사람의 풀이 중, s와 t 문자열을 sort하고 값이 일치하는 방법이 있었다.

def sol(s, t):
	return sorted(s) == sorted(t)  # 43ms

0개의 댓글