author: Blankj blog : http://blankj.com time : 2017/10/18 desc :
| 16 | * </pre> |
| 17 | */ |
| 18 | public class Solution { |
| 19 | public List<List<String>> groupAnagrams(String[] strs) { |
| 20 | if (strs == null || strs.length == 0) return Collections.emptyList(); |
| 21 | List<List<String>> list = new ArrayList<>(); |
| 22 | Map<String, Integer> hash = new HashMap<>(); |
| 23 | int i = 0; |
| 24 | for (String str : strs) { |
| 25 | char[] c = str.toCharArray(); |
| 26 | Arrays.sort(c); |
| 27 | String sortStr = String.valueOf(c); |
| 28 | if (!hash.containsKey(sortStr)) { |
| 29 | hash.put(sortStr, i++); |
| 30 | List<String> sub = new ArrayList<>(); |
| 31 | sub.add(str); |
| 32 | list.add(sub); |
| 33 | } else { |
| 34 | list.get(hash.get(sortStr)).add(str); |
| 35 | } |
| 36 | } |
| 37 | return list; |
| 38 | } |
| 39 | |
| 40 | public static void main(String[] args) { |
| 41 | Solution solution = new Solution(); |
| 42 | System.out.println(solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"})); |
| 43 | } |
| 44 | } |
nothing calls this directly
no outgoing calls
no test coverage detected