์• ์ •์ฝ”๋”ฉ ๐Ÿ’ป

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

 

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

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.

 

๋‚ด๊ฐ€ ํ‘ผ๊ฑฐ:

์‚ฌ์ „ ์กฐ๊ฑด์œผ๋กœ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋ฉด Anagram ์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ”๋กœ False ๋ฐ˜ํ™˜ํ–ˆ๊ณ 

ํ•ด๋‹น ๋ฌธ์ž์—ด์„ ํ•˜๋‚˜์”ฉ ์ฐพ์•„ ์—†์• ๋Š”๋ฐ exception ์ด ๋‚˜๋ฉด False๋กœ ๋ฐ˜ํ™˜ํ–ˆ๋‹ค.

์ •๋ ฌ์„ ํ•ด์„œ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์ง€๋งŒ ๊ทธ๋Ÿฌ๋ฉด... ์˜๋ฏธ๊ฐ€...

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

        if len(s_array) != len(t_array):
            return False;

        s_array = list(s);
        t_array = list(t);
            
        for s in s_array:
            try:
                t_array.remove(s)
            except ValueError:
                return False;
        return True;

 

๊ดœ์ฐฎ๋‹ค๊ณ  ์ƒ๊ฐํ•œ ํ’€์ด ์ค‘ ํ•œ๊ฐœ:

ํŒŒ์ด์ฌ์—์„œ๋Š” ๋ฌธ์ž์—ด์— .count ๋ฅผ ํ•˜๋ฉด ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ๋ช‡๊ฐœ ์žˆ๋Š”์ง€ ํ™•์ธํ•ด ์ค€๋‹ค. ๊ฐœ๊ฟ€์ด๋„ค;

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        flag = True
        if len(s) != len(t): 
            flag = False
        else:
            letters = "abcdefghijklmnopqrstuvwxyz"
            for letter in letters:
                if s.count(letter) != t.count(letter):
                    flag = False
                    break
        return flag

 

๋ฐ˜์‘ํ˜•

'์•Œ๊ณ ๋ฆฌ์ฆ˜ > Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

347. Top K Frequent Elements  (0) 2023.08.20
49. Group Anagrams  (0) 2023.08.18
1. Two Sum  (0) 2023.08.16
217. Contains Duplicate  (0) 2023.08.10