Skip to content

Commit 61b9909

Browse files
committed
solve: Valid Anagram
1 parent 9290955 commit 61b9909

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

valid-anagram/JustHm.swift

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
func isAnagram(_ s: String, _ t: String) -> Bool {
3+
// s 문자열의 문자를 키로 빈도수를 값으로 저장
4+
var baseDict = Dictionary(s.map{($0,1)}, uniquingKeysWith: +)
5+
6+
for char in t { // t를 반복하면서 존재하는지 확인, 만약 없다면 return false
7+
guard baseDict[char] != nil, baseDict[char] != 0
8+
else { return false }
9+
10+
baseDict[char]? -= 1
11+
if baseDict[char] == 0 {
12+
baseDict.removeValue(forKey: char)
13+
}
14+
}
15+
return baseDict.isEmpty
16+
}
17+
}
18+
19+
// MARK: 가장 간단한 방법
20+
class Solution2 {
21+
func isAnagram(_ s: String, _ t: String) -> Bool {
22+
s.sorted() == t.sorted()
23+
}
24+
}
25+
26+
// MARK: 실행속도가 가장 빠름
27+
class Solution3 {
28+
func isAnagram(_ s: String, _ t: String) -> Bool {
29+
guard s.count == t.count else { return false }
30+
31+
let sCharCount = getCharacterCount(s)
32+
let tCharCount = getCharacterCount(t)
33+
// 반환된 배열이 동일하면 애너그램
34+
return sCharCount == tCharCount
35+
}
36+
// 배열로 문자 빈도수를 처리 및 저장
37+
private func getCharacterCount(_ str: String) -> [Int] {
38+
var charCount = [Int](repeating: 0, count: 26)
39+
let aAsciiValue = Character("a").asciiValue ?? 0
40+
41+
for char in str.utf8 {
42+
charCount[Int(char - aAsciiValue)] += 1
43+
}
44+
45+
return charCount
46+
}
47+
}

0 commit comments

Comments
 (0)