leetcode242 Anagram

leetcode242 Anagram

Given two strings s and t, write a function to determine if t is an alphabetic word of s.
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-anagram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Example:
1、
Input: s = “anagram”, t = “nagaram”
Output: true

2、
Input: s = “rat”, t = “car”
Output: false

Thought and method:
To this question, we may have several ways.

1、sort and verify
It is a easy and simple way to think of. We can obviously get the two same strings after sorting if they are anagrams.
However, it is not so appropriate to use it in the Go due to the high time and space consume.Besides, other ways are better.
Time complexity: O(nlogn)
Space complexity: O(1)

2、use harsh
We can simply use a counter to add the numbers of 26 letters showing in the string s, and then subtract the number of 26 letters in the string t.
Finally, counter equals 0 leading to “true” while other numbers leading to “False”

3、similar to harsh but only use array
Considering 26 letters, we can do some change. Using to counters to add the numbers of 26 letters in both strings. If they are equal, the resuly must be “true”.

Surprisingly, using only array actually raise the perfomance in time despite the same Algorithm ideas in two ways.

Both
Time complexity: O(n)
Space complexity: O(1)

Code:
2、

func isAnagram(s string, t string) bool {
    if len(s) != len(t) {
        return false
    }

    Counter := make(map[string]int)

    for i := 0; i < len(s); i++ {
        Counter[string(s[i])] ++
    }
    for j := 0; j < len(t); j ++ {
        Counter[string(t[j])] --
    }

    for _, m := range Counter {
        if m != 0 {
            return false
        }
    }
    return true
}

3、

func isAnagram(s string, t string) bool {
	a := [26]int{}
	b := [26]int{}

	for _, v := range s {
		a[v-'a'] ++
	}

	for _, v := range t {
		b[v-'a'] ++
	}
	return a == b
}

Test
Input: s = “anagram”, t = “nagaram”
在这里插入图片描述
Input: s = “rat”, t = “car”
在这里插入图片描述
leetcode comparison of operation results
在这里插入图片描述
The former one uses way 2, the latter one uses way 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值