anagram means after sorted they have the same string
Collections.sort(item);
Group anagrams together
s= ["eat", "tea", "tan", "ate", "nat", "bat"]
Return
[
["ate", "eat", "tea"]
["nat", "tan"],
["bat"]
]
2. Implementation
Q1: Return List<List<String>>?
A1: since the size of string array is dynamic
Input:["tea","and","ate","eat","den"]
Output:[["tea","ate","eat"],["and"],["den"]]
Expected:[["den"],["and"],["ate","eat","tea"]]
NOTE: each inner list's elements must follow the lexicographic order
==> Collections.sort(item);
NOTE:
for (List<String> value: map.values()) {
Output:[["tea","ate","eat"],["and"],["den"]]
Expected:[["den"],["and"],["ate","eat","tea"]]
NOTE: each inner list's elements must follow the lexicographic order
==> Collections.sort(item);
NOTE:
for (List<String> value: map.values()) {
// //3. Similar OnesTime :O(m*n) or O(m+n) , m is length of string and n is number of string in string array//Time:O(n* mlogm), n is size of string array, m is the length of each string, assume they are the same public List> groupAnagrams(String[] strs) { List
> res = new List
>(); if (strs == null || strs.length == 0) return res; //HashTable > table = new HashTable > (); HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for (int i = 0; i < strs.length; i++) { char[] charArr = strs[i].toCharArray(); Arrays.sort(charArr); String str = new String(charArr); //if ( table.containsKey() ) if (map.containsKey(str)) { //table.get(key).add( strs[i]); map.get(str).add( strs[i] ); } else { //for (int j = 0 ; j< strs[i];j++) ///{ //(int) (strs[i].charAt(j)-'a') // } List<String> item = new ArrayList<String> (); item.add(strs[i]); //table.put(, item); map.put(str, item) } } //NOTE:return all the map values,(map.keySet()) for (List value: map.values()) { List<String> item = new ArrayList<String> (value); Collections.sort(item); if (item.size() >0) res.add(item); } return res; }
(E) Valid Anagram
(E) Group Shifted Strings
No comments:
Post a Comment