题目链接:https://leetcode.com/problems/anagrams/
题目:
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:
- For the return value, each inner list‘s elements must follow the lexicographic order.
- All inputs will be in lower-case.
思路:
将每个字符串的字符排序,将排序后的相同字符串保存在map中,最后要对结果字典序排序。
算法:
[java] view
plain copy
- public List<List<String>> groupAnagrams(String[] strs) {
- List<List<String>> strss = new ArrayList<List<String>>();
- HashMap<String, List<String>> maps = new HashMap<String, List<String>>();
- for (String s : strs) { // 字符串内排序,并保存对应关系
- char c[] = s.toCharArray();
- Arrays.sort(c);
- if (!maps.containsKey(String.valueOf(c))) {
- List<String> l = new ArrayList<String>();
- l.add(s);
- maps.put(String.valueOf(c), l);
- } else {
- List<String> l = maps.get(String.valueOf(c));
- l.add(s);
- maps.put(String.valueOf(c), l);
- }
- }
- Iterator<String> set = maps.keySet().iterator();
- while (set.hasNext()) {
- List<String> l = maps.get(set.next());
- Collections.sort(l); // 因为要求list内部字符串要字典序,所以对list进行排序,可以用collections对list排序
- strss.add(l);
- }
- return strss;
- }
时间: 2024-08-08 13:47:21