booking——all_anagram_groups

题目

Implement a function all_anagram_groups() that, 
given many input strings, will identify and group words that are anagrams of each other.

An anagram is word that is just a re-arrangement of the characters of another word,
like "reap" and "pear" and "a per" (whitespace is ignored).
But "pear" and "rep" are not, since "rep" does not have an "a". 
Also, "the" and "thee" are not anagrams, because "the" only has one "e".

Given this example input:
[ "pear","dirty room","amleth","reap","tinsel","tesla","hamlet","dormitory","listen","silent" ]

The output should be an array-of-arrays (or list-of-lists)
[
["pear","reap"],
["dirty room","dormitory"],
["amleth","hamlet"],
["tinsel","listen","silent"],
["tesla"]
]

这个没有什么难点,顺序操作即可
leecode链接:https://leetcode.com/problems/group-anagrams/

type Item struct {
	mp map[uint8]int
	index int
}

func all_anagram_groups(input []string) [][]string {
	var mps []*Item
	for i := 0; i < len(input); i++ {
		mp := make(map[uint8]int)
		for j := 0; j < len(input[i]); j++ {
			if input[i][j] == ' ' {
				continue
			}
			mp[input[i][j]]++
		}
		mps = append(mps, &Item{
			mp: mp,
			index: i,
		})
	}
	var groups [][]*Item
	for i := 0; i < len(mps); i++ {
		matched := false
		for j := 0; j < len(groups); j++ {
			if isMapEqual(mps[i].mp, groups[j][0].mp) {
				groups[j] = append(groups[j], mps[i])
				matched = true
				break
			}
		}
		if !matched {
			groups = append(groups, []*Item{mps[i]})
		}
	}
	var res [][]string
	for _, group := range groups {
		var tmp []string
		for _, v := range group {
			tmp = append(tmp, input[v.index])
		}
		res = append(res, tmp)
	}
	return res
}

func isMapEqual(mp1 map[uint8]int, mp2 map[uint8]int) bool {
	if len(mp1) != len(mp2) {
		return false
	}
	for k, v := range mp1 {
		vv, ok := mp2[k]
		if !ok {
			return false
		}
		if vv != v {
			return false
		}
	}
	return true
}

参考资料

https://www.1point3acres.com/bbs/thread-143340-1-1.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值