美文网首页
Group Anagrams go语言实现

Group Anagrams go语言实现

作者: fjxCode | 来源:发表于2018-09-22 15:30 被阅读0次

Group Anagrams

题目描述

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.

思路:

  • 以排序后单词为键,加入哈希表。遍历哈希打印

细节:

  • 实现接口以调用sort.Sort()
  • 哈希表put直接用append,避免判断是否存在,和初始化[]string的值类型。

解:

package main

import "sort"

func groupAnagrams(strs []string) [][]string {
    var hashmap map[string][]string
    hashmap = make(map[string][]string)
    for _,elem := range strs {
        elemSorted := stringSort(elem)
        //use append to avoid "contains()" and make()
        hashmap[elemSorted] = append(hashmap[elemSorted],elem)
    }

    var res [][]string
    for _,value := range hashmap {
        res = append(res,value)
    }
    return res
}

//go用sort内置包实现字串排序的方法
func stringSort(s string) string {
    sArr := []rune(s)
    sort.Sort(RuneSlice(sArr))
    return string(sArr)

}
type RuneSlice []rune

func (rs RuneSlice)Len() int {
    return len(rs)
}
func (rs RuneSlice)Less(i,j int) bool {
    return rs[i] < rs[j]
}
func (rs RuneSlice)Swap(i,j int)  {
    rs[i],rs[j] = rs[j],rs[i]
}

相关文章

网友评论

      本文标题:Group Anagrams go语言实现

      本文链接:https://www.haomeiwen.com/subject/nohxoftx.html