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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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 ...
閱讀 3234·2021-11-18 10:02
閱讀 1936·2021-09-22 10:54
閱讀 2989·2019-08-30 15:43
閱讀 2576·2019-08-30 13:22
閱讀 1575·2019-08-29 13:57
閱讀 1041·2019-08-29 13:27
閱讀 731·2019-08-26 14:05
閱讀 2512·2019-08-26 13:30