Group Anagrams
原题信息
题号49,难度中等,涉及考点:数组、Map
题目
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
示例
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""] Output: [[""]]
Example 3:
Input: strs = ["a"] Output: [["a"]]
备注
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] consists of lower-case English letters.
分析
Anagram (回文构词法) 是指打乱字母顺序从而得到新的单词,回文构词法有个特点:单词里的字母种类和数目没有改变,只是改变字母的排列顺序,因此,将几个单词按照字母顺序排序后,若相等,则属于同一组anagrams。
一开始的思路:拷贝一份数组,然后排序,相同的放在hash表里有相同的坐标,返回坐标相同的数组元素,后来被启发可以绑定key值,根据相同key值返回。
js题解
作者:barba-lee
链接:https://leetcode-cn.com/problems/group-anagrams/solution/shi-yong-mapsan-xing-jie-jue-yong-shi-ji-i8ly/
思路
1. 定义map存储
2. 字符串转数组->排序->转字符串为key(将所有异位词排序为同一单词,作为key)
3. 根据key插入map
4. map传数组输出
题解
/** * @param {string[]} strs * @return {string[][]} */
var groupAnagrams = function(strs) { let map = new Map(); strs.forEach((str) => { const key = str.split("").sort().join(""); map.has(key) ? map.get(key).push(str) : map.set(key, [str]); }); return Array.from(map.values());
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!