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 |