repl.it
@shachopin/

Group Anagrams

Java

No description

fork
loading
Files
  • Main.java
  • jdt.ls-java-project
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

design key
key是排序后的字符
value 是list of strs with 排序后same key
MySolution on lintcode 171 Anagrams:

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        // write your code here
        List<String> ans = new ArrayList<>();
        Map<String, List<String>> strToList = new HashMap<>();
        
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortedString = String.valueOf(chars);
            strToList.putIfAbsent(sortedString, new ArrayList<String>());
            strToList.get(sortedString).add(str);
        }
        
        for (List<String> strList : strToList.values()) {
            if (strList.size() > 1) { //单身汉我们不要
                ans.addAll(strList);
            }
            
        }
        return ans;
    }
}


和上题一个思路
MySolution on lintcode 772 Group Anagrams:

public class Solution {
    /**
     * @param strs: the given array of strings
     * @return: The anagrams which have been divided into groups
     */
    public List<List<String>> groupAnagrams(String[] strs) {
        // write your code here
        Map<String, List<String>> strToList = new HashMap<>();
        
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortedStr = String.valueOf(chars);
            
            strToList.putIfAbsent(sortedStr, new ArrayList<String>());
            strToList.get(sortedStr).add(str);
        }
        
        return new ArrayList<>(strToList.values());
    }
}