首页 > 其他分享 >[LeetCode]Group Anagrams

[LeetCode]Group Anagrams

时间:2023-02-02 15:36:14浏览次数:40  
标签:map Group String Anagrams get num ans new LeetCode


Question
Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:

[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
Note: All inputs will be in lower-case.


本题难度Medium。

【思路】
对单词进行排序得到​​​key​​​,看是否为同一个单词。同时利用一个HashMap变量保存​​<key,list序号>​​。

【复杂度】
时间 O(NKlogK) 空间 O(N)

【注意】
本题的单词都是lower-case。

【代码】

public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
//require
List<List<String>> ans=new ArrayList<>();
if(strs==null)
return ans;
Map<String,Integer> map=new HashMap<String,Integer>();
//invariant
int num=0;
for(String s:strs){
String r=sort(s);
if(map.containsKey(r)){
int index=map.get(r);
ans.get(index).add(s);
}else{
map.put(r,num);
ans.add(new ArrayList<String>());
ans.get(num).add(s);
num++;
}
}
//ensure
return ans;
}
private String sort(String s){
char[] chars=s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}


标签:map,Group,String,Anagrams,get,num,ans,new,LeetCode
From: https://blog.51cto.com/u_9208248/6033693

相关文章

  • [LeetCode]Jump Game II
    QuestionGivenanarrayofnon-negativeintegers,youareinitiallypositionedatthefirstindexofthearray.Eachelementinthearrayrepresentsyourmaximu......
  • [LeetCode]Rotate Image
    QuestionYouaregivenannxn2Dmatrixrepresentinganimage.Rotatetheimageby90degrees(clockwise).Followup:Couldyoudothisin-place?本题难度Mediu......
  • LeetCode 1143_ 最长公共子序列
    LeetCode1143:最长公共子序列题目给定两个字符串text1和text2,返回这两个字符串的最长公共子序列的长度。如果不存在公共子序列,返回0。一个字符串的子序列......
  • 【DFS】LeetCode 124. 二叉树中的最大路径和
    题目链接124.二叉树中的最大路径和思路一个子树内部的最大路径和=左子树提供的最大路径和+根节点值+右子树提供的最大路径和。即dfs(root.left)+root.val+dfs(r......
  • LeetCode - 709. To Lower Case
    题目ImplementfunctionToLowerCase()thathasastringparameterstr,andreturnsthesamestringinlowercase.Example1:Input:"Hello"Output:"hello"Example2:......
  • LeetCode - 344. Reverse String
    题目Writeafunctionthatreversesastring.Theinputstringisgivenasanarrayofcharacterschar[].Donotallocateextraspaceforanotherarray,youmust......
  • LeetCode - 771. Jewels and Stones
    题目You’regivenstrings​​J​​​representingthetypesofstonesthatarejewels,and​​S​​representingthestonesyouhave.EachcharacterinSisa......
  • LeetCode - 412. Fizz Buzz
    题目Writeaprogramthatoutputsthestringrepresentationofnumbersfrom1ton.Butformultiplesofthreeitshouldoutput“Fizz”insteadofthenumberand......
  • Leetcode之二分思想
    友情提示:代码在这里本文参照该仓库学习,大家可以star二分查找原理1.正常实现publicclassbinarySearch{publicintBinarySearch(int[]nums,intkey){......
  • 代码随想录算法训练营day16 | leetcode ● 104.二叉树的最大深度 559.n叉树的最大深
    基础知识二叉树的多种遍历方式,每种遍历方式各有其特点LeetCode104.二叉树的最大深度分析1.0往下遍历深度++,往上回溯深度--classSolution{intdeep=0,max=......