Valid Anagram

View on LeetCode

Question

Given two strings, check if one is an anagram of the other. An anagram means both strings contain the same characters, just in a different order.

You must return true if they are anagrams, false otherwise.

Example

Input: "listen", "silent"

Output: true

Explanation: Both strings use the same letters.


Input: "rat", "car"

Output: false

Explanation: The characters don't match.


Input: "a", "a"

Output: true

Explanation: Same one-character string.

My Notes

package main

import (
    "fmt"
)

func main() {
    result := isAnagram("anagram", "nagaram")
    fmt.Println(result)
}

func isAnagram(s string, t string) bool {
    lookup := make(map[rune]int)

    if len(s) != len(t) {
        return false
    }

    for _, ch := range s {
        lookup[ch]++
    }

    for _, ch := range t {
        if _, ok := lookup[ch]; !ok {
            return false
        }
        lookup[ch]--
        if lookup[ch] == 0 {
            delete(lookup, ch)
        }
    }

    return true
}