49. 字母异位词分组
生活随笔
收集整理的這篇文章主要介紹了
49. 字母异位词分组
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
49. 字母異位詞分組
給你一個(gè)字符串?dāng)?shù)組,請(qǐng)你將 字母異位詞 組合在一起??梢园慈我忭樞蚍祷亟Y(jié)果列表。
字母異位詞 是由重新排列源單詞的字母得到的一個(gè)新單詞,所有源單詞中的字母都恰好只用一次。
- 示例 1:
輸入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
輸出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
- 示例 2:
輸入: strs = [""]
輸出: [[""]]
- 示例 3:
輸入: strs = [“a”]
輸出: [[“a”]]
解題思路
使用將單詞中每個(gè)字符以及其對(duì)應(yīng)的出現(xiàn)的次數(shù)拼接成為key
代碼
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String,List<String>> map=new HashMap<>();for(String s:strs){int[] cnt=new int[26];for(int i=0;i<s.length();i++)cnt[s.charAt(i)-'a']++;StringBuilder sb=new StringBuilder();for(int i=0;i<26;i++)if(cnt[i]>=0)sb.append((char)(i+'a')).append(cnt[i]);String temp=sb.toString();if(!map.containsKey(temp))map.put(temp,new ArrayList<>());map.get(temp).add(s);}List<List<String>> res=new ArrayList<>();for(List l:map.values())res.add(l);return res;} }總結(jié)
以上是生活随笔為你收集整理的49. 字母异位词分组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 孕妇梦到青蛙是胎梦吗
- 下一篇: 722. 删除注释