這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return 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遍曆一次,遍曆s的時候,用字母當關鍵字,統計字母出現的次數,第二次遍曆的時候,每遍曆到一個字母就讓這個字母的計數減一,這樣就能做判斷了
題目中提到了unicode的問題,在go語言中可以輕鬆處理,在對字串使用for range語句的時候,提取出來的value不是byte類型而是rune類型的,一個rune就能對應一個unicode碼
func isAnagram(s string, t string) bool { if (len(s) != len(t)) { return false } m := map[string]int{} for _, v := range s { key, ok := m[string(v)] if !ok { m[string(v)] = 1 } else { m[string(v)] = key + 1 } } for _, v := range t { key, ok := m[string(v)] if !ok { return false } if key == 0 { return false } m[string(v)] = key - 1 } return true}