Problem
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.
class Solution { public List> groupAnagrams(String[] strs) { List
> res = new ArrayList<>(); if (strs == null || strs.length == 0) return res; Map
> map = new HashMap<>(); //use HashMap to store grouped anagrams for (String str: strs) { char[] charArray = str.toCharArray(); Arrays.sort(charArray); //sort each string to match existing key String anagram = String.valueOf(charArray); if (!map.containsKey(anagram)) { //if not existed, create a list map.put(anagram, new ArrayList<>()); } map.get(anagram).add(str); //put the original string into its anagram group } for (Map.Entry > entry: map.entrySet()) { //use Map.Entry from map.entrySet() to iterate List anagrams = entry.getValue(); Collections.sort(anagrams); //sort it in lexicographic order res.add(anagrams); } return res; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/77048.html
摘要:排序法复杂度时间空间思路因为变形词两个单词对应字母出现的次数都相同,所以如果将两个单词按字母顺序排序,肯定会变为一个字符串,如果字符串不相同,则不是变形词。 Valid Anagram Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = a...
摘要:题目链接题目分析判断给定的两个单词是否同构。即,重新排列组合所出现的字母后得到另一个单词。思路拆分成数组后,排序,再拼起来。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D85 242. Valid Anagram 题目链接 242. Valid Anagram 题目分析 判断给定的两个单词是否同构。即,重新排列组合所出现的字母后得到另一个单词。 思路 拆分成数组后,排序,再拼起来...
Problem Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. We want to find an index mapping P, from A to B. A mapping...
Problem Given a string s and a non-empty string p, find all the start indices of ps anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be...
Problem Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. For example, tars and rats are similar (swapping at positions 0 and 2), and rats ...
阅读 3218·2021-11-18 10:02
阅读 1906·2021-09-22 10:54
阅读 2970·2019-08-30 15:43
阅读 2557·2019-08-30 13:22
阅读 1550·2019-08-29 13:57
阅读 1009·2019-08-29 13:27
阅读 702·2019-08-26 14:05
阅读 2490·2019-08-26 13:30