넘치게 채우기

[LeetCode] 242. Valid Anagram 본문

PS/LeetCode

[LeetCode] 242. Valid Anagram

riveroverflow 2023. 8. 27. 15:58
728x90
반응형

https://leetcode.com/problems/valid-anagram/description/?envType=study-plan-v2&envId=top-interview-150 

 

Valid Anagram - LeetCode

Can you solve this real interview question? Valid Anagram - 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

leetcode.com

문제 유형 : 해시 테이블

문제 난이도 : Easy

 

문제

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.

 

두 문자열 s와 t가 주어질 때, t가 s의 애너그램이면 true를, 아니면 false를 반환하시오.

 

애너그램은 기존 글자들을 사용하여 순서를 바꿔 재조합한 단어 또는 절입니다.

 

풀이

key = 문자, value = 개수의 형태를 가진 해시 테이블을 두 개 만들고, 각 문자열의 문자의 개수를 받는다.

두 해시 테이블의 key에 따른 value가 모두 같으면 true를, 아니면 false를 반환한다.

 

코드

C++

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> m;
        unordered_map<char, int> n;

        for(char ch : s) {
            m[ch]++;
        }

        for(char ch : t) {
            n[ch]++;
        }

        for(int i = 0; i < 26; i++) {
            if(m['a' + i] != n['a' + i]) return false;
        }

        return true;
    }
};

 

Python3

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        m = {}
        n = {}

        for ch in s:
            m[ch] = m.get(ch, 0) + 1
        
        for ch in t:
            n[ch] = n.get(ch, 0) + 1  

        for i in range(26):
            if m.get(chr(ord('a') + i), 0) != n.get(chr(ord('a') + i), 0):
                return False
        
        return True

 

Java

 

import java.util.Hashtable;

class Solution {
    public boolean isAnagram(String s, String t) {
        Hashtable<Character, Integer> m = new Hashtable<>();
        Hashtable<Character, Integer> n = new Hashtable<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            m.put(ch, m.getOrDefault(ch, 0) + 1);
        }

        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            n.put(ch, n.getOrDefault(ch, 0) + 1);
        }

        for (int i = 0; i < 26; i++) {
            char currentChar = (char) ('a' + i);
            if (!m.getOrDefault(currentChar, 0).equals(n.getOrDefault(currentChar, 0))) {
                return false;
            }
        }

        return true;
    }
}
728x90
반응형