|
30 | 30 |
|
31 | 31 | <!-- 这里可写通用的实现逻辑 -->
|
32 | 32 |
|
| 33 | +遍历字符串,将每个字符串按照字符字典序排序后得到一个新的字符串,将相同的新字符串放在哈希表的同一个 key 对应 value 列表中。 |
| 34 | + |
| 35 | +| key | value | |
| 36 | +| ------- | ----------------------- | |
| 37 | +| `"aet"` | `["eat", "tea", "ate"]` | |
| 38 | +| `"ant"` | `["tan", "nat"] ` | |
| 39 | +| `"abt"` | `["bat"] ` | |
| 40 | + |
| 41 | +最后返回哈希表的 value 列表即可。 |
| 42 | + |
33 | 43 | <!-- tabs:start -->
|
34 | 44 |
|
35 | 45 | ### **Python3**
|
36 | 46 |
|
37 | 47 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
38 | 48 |
|
39 | 49 | ```python
|
40 | | - |
| 50 | +class Solution: |
| 51 | + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: |
| 52 | + chars = collections.defaultdict(list) |
| 53 | + for s in strs: |
| 54 | + k = ''.join(sorted(list(s))) |
| 55 | + chars[k].append(s) |
| 56 | + return list(chars.values()) |
41 | 57 | ```
|
42 | 58 |
|
43 | 59 | ### **Java**
|
44 | 60 |
|
45 | 61 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
46 | 62 |
|
47 | 63 | ```java
|
| 64 | +class Solution { |
| 65 | + public List<List<String>> groupAnagrams(String[] strs) { |
| 66 | + Map<String, List<String>> chars = new HashMap<>(); |
| 67 | + for (String s : strs) { |
| 68 | + char[] t = s.toCharArray(); |
| 69 | + Arrays.sort(t); |
| 70 | + String k = new String(t); |
| 71 | + chars.computeIfAbsent(k, key -> new ArrayList<>()).add(s); |
| 72 | + } |
| 73 | + return new ArrayList<>(chars.values()); |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
| 77 | + |
| 78 | +### **C++** |
| 79 | + |
| 80 | +```cpp |
| 81 | +class Solution { |
| 82 | +public: |
| 83 | + vector<vector<string>> groupAnagrams(vector<string> &strs) { |
| 84 | + unordered_map<string, vector<string>> chars; |
| 85 | + for (auto s : strs) |
| 86 | + { |
| 87 | + string k = s; |
| 88 | + sort(k.begin(), k.end()); |
| 89 | + chars[k].emplace_back(s); |
| 90 | + } |
| 91 | + vector<vector<string>> res; |
| 92 | + for (auto it = chars.begin(); it != chars.end(); ++it) |
| 93 | + { |
| 94 | + res.emplace_back(it->second); |
| 95 | + } |
| 96 | + return res; |
| 97 | + } |
| 98 | +}; |
| 99 | +``` |
48 | 100 |
|
| 101 | +### **Go** |
| 102 | + |
| 103 | +```go |
| 104 | +func groupAnagrams(strs []string) [][]string { |
| 105 | + chars := map[string][]string{} |
| 106 | + for _, s := range strs { |
| 107 | + key := []byte(s) |
| 108 | + sort.Slice(key, func(i, j int) bool { |
| 109 | + return key[i] < key[j] |
| 110 | + }) |
| 111 | + chars[string(key)] = append(chars[string(key)], s) |
| 112 | + } |
| 113 | + var res [][]string |
| 114 | + for _, v := range chars { |
| 115 | + res = append(res, v) |
| 116 | + } |
| 117 | + return res |
| 118 | +} |
49 | 119 | ```
|
50 | 120 |
|
51 | 121 | ### **...**
|
|
0 commit comments