242. Valid Anagram #
Problem #
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?
Problem Summary #
Given 2 strings s and t, if every letter in t exists in s, output true; otherwise output false.
Solution Approach #
This problem can be solved using a counting table. First store each letter in s in an array with a capacity of 26, where each index corresponds to one of the 26 letters in order. Each letter in s corresponds to a letter in the table, and the count is incremented by 1 each time it appears. Then scan the string t, and decrement the count in the table by one each time a letter appears. If all letters appear, the final values in the table must all be 0. Finally, check whether all values in the table are 0; if any non-0 number exists, output false.
Code #
package leetcode
// Solution 1
func isAnagram(s string, t string) bool {
alphabet := make([]int, 26)
sBytes := []byte(s)
tBytes := []byte(t)
if len(sBytes) != len(tBytes) {
return false
}
for i := 0; i < len(sBytes); i++ {
alphabet[sBytes[i]-'a']++
}
for i := 0; i < len(tBytes); i++ {
alphabet[tBytes[i]-'a']--
}
for i := 0; i < 26; i++ {
if alphabet[i] != 0 {
return false
}
}
return true
}
// Solution 2
func isAnagram1(s string, t string) bool {
hash := map[rune]int{}
for _, value := range s {
hash[value]++
}
for _, value := range t {
hash[value]--
}
for _, value := range hash {
if value != 0 {
return false
}
}
return true
}