字母异位词分组 (groupAnagrams)
2024年11月12日小于 1 分钟约 29 字...
字母异位词分组 (groupAnagrams)
https://leetcode.cn/problems/group-anagrams
解法思路
Golang
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"}
results := groupAnagrams(strs)
fmt.Println("results", results)
}
// 暴力求解
func groupAnagrams(strs []string) [][]string {
hasMap := map[string][]string{}
for _, v := range strs {
splitStr := strings.Split(v, "")
sort.Strings(splitStr)
sortStr := strings.Join(splitStr, "")
hasMap[sortStr] = append(hasMap[sortStr], v)
}
returnVal := [][]string{}
for _, v := range hasMap {
returnVal = append(returnVal, v)
}
return returnVal
}
JavaScript
var groupAnagrams = function (strs) {
const hasMap = {};
for (let i = 0; i < strs.length; i++) {
const el = strs[i];
let splitStr = el.split('');
splitStr = splitStr.sort();
let sortStr = splitStr.join('');
if (hasMap[sortStr]) {
hasMap[sortStr].push(el);
} else {
hasMap[sortStr] = [el];
}
}
let returnVal = [];
for (const key in hasMap) {
if (Object.hasOwnProperty.call(hasMap, key)) {
const el = hasMap[key];
returnVal.push(el);
}
}
return returnVal;
};
// 代码执行块
(function () {
const strs = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'];
const result = groupAnagrams(strs);
console.log('result', result);
})();
你认为这篇文章怎么样?
- 0
- 0
- 0
- 0
- 0
- 0