Leetcode: 242. Valid Anagram
- Primary idea: Compare the character freequencies of the 2 arrays
- Time Complexity: O(n)
- Space Complexity: O(n)
func isAnagram(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else { return false }
var dict = [Character: Int]()
for char in s {
dict[char, default: 0] += 1
}
for char in t {
if let count = dict[char], count > 0 {
dict[char] = count - 1
} else {
return false
}
}
return true
}
print(isAnagram("anagram", "nagaram")) // true
print(isAnagram("rat", "car")) // false