標籤:nta cal dap esc determine let hat contains case
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"Output: true
Example 2:
Input: s = "rat", t = "car"Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
給定兩個字串 s 和 t ,編寫一個函數來判斷 t 是否是 s 的一個字母異位詞。
樣本 1:
輸入: s = "anagram", t = "nagaram"輸出: true
樣本 2:
輸入: s = "rat", t = "car"輸出: false
說明:
你可以假設字串只包含小寫字母。
進階:
如果輸入字串包含 unicode 字元怎麼辦?你能否調整你的解法來應對這種情況?
32ms
1 class Solution { 2 func isAnagram(_ s: String, _ t: String) -> Bool { 3 4 let chars_S = s.unicodeScalars 5 var counter_S = Array(repeating: 0, count: 26) 6 let chars_T = t.unicodeScalars 7 var counter_T = Array(repeating: 0, count: 26) 8 9 for char in chars_S {10 let index = Int(char.value - 97)11 counter_S[index] += 112 }13 14 for char in chars_T {15 let index = Int(char.value - 97)16 counter_T[index] += 117 }18 return counter_T == counter_S19 }20 }
32ms
1 class Solution { 2 func isAnagram(_ s: String, _ t: String) -> Bool { 3 guard s.count == t.count else { 4 return false 5 } 6 var occurances = [Int](repeating: 0, count: 26) 7 let aValue: UInt8 = 97 8 for char in s.utf8 { 9 occurances[Int(char - aValue)] += 110 }11 for char in t.utf8 {12 occurances[Int(char - aValue)] -= 113 }14 for value in occurances {15 if value != 0 {16 return false17 }18 }19 return true20 }21 }
48ms
1 class Solution {2 func isAnagram(_ s: String, _ t: String) -> Bool {3 return t.unicodeScalars.reduce(into: [:]) { $0[$1, default: 0] += 1 } == s.unicodeScalars.reduce(into: [:]) { $0[$1, default: 0] += 1 }4 }5 }
64ms
1 extension Character { 2 3 var ascii: Int { 4 return Int(unicodeScalars.first!.value) 5 } 6 7 } 8 9 class Solution {10 func isAnagram(_ s: String, _ t: String) -> Bool {11 var table = [Int](repeating: 0, count: 128)12 13 for char in s {14 table[char.ascii] += 115 }16 17 for char in t {18 table[char.ascii] -= 119 }20 21 for ascii in 97...122 {22 if table[ascii] != 0 {23 return false24 }25 }26 27 return true28 }29 }
242. 有效字母異位詞 | Valid Anagram