面试题 10.02:变位词组

This commit is contained in:
huangge1199@hotmail.com 2021-07-18 17:19:37 +08:00
parent 4f0d6cdc0b
commit c59a203627
3 changed files with 77 additions and 1 deletions

View File

@ -0,0 +1,55 @@
//编写一种方法对字符串数组进行排序将所有变位词组合在一起变位词是指字母相同但排列不同的字符串
//
// 注意本题相对原题稍作修改
//
// 示例:
//
// 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
//输出:
//[
// ["ate","eat","tea"],
// ["nat","tan"],
// ["bat"]
//]
//
// 说明
//
//
// 所有输入均为小写字母
// 不考虑答案输出的顺序
//
// Related Topics 哈希表 字符串 排序
// 👍 66 👎 0
package leetcode.editor.cn;
import java.util.*;
//面试题 10.02:变位词组
class GroupAnagramsLcci{
public static void main(String[] args) {
//测试代码
Solution solution = new GroupAnagramsLcci().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for (String str:strs){
char[] chars = str.toCharArray();
Arrays.sort(chars);
List<String> list = map.getOrDefault(new String(chars),new ArrayList<>());
list.add(str);
map.put(new String(chars),list);
}
List<List<String>> result = new ArrayList<>();
for (String key: map.keySet()){
result.add(map.get(key));
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,21 @@
<p>编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。</p>
<p><strong>注意:</strong>本题相对原题稍作修改</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> <code>[&quot;eat&quot;, &quot;tea&quot;, &quot;tan&quot;, &quot;ate&quot;, &quot;nat&quot;, &quot;bat&quot;]</code>,
<strong>输出:</strong>
[
[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;],
[&quot;nat&quot;,&quot;tan&quot;],
[&quot;bat&quot;]
]</pre>
<p><strong>说明:</strong></p>
<ul>
<li>所有输入均为小写字母。</li>
<li>不考虑答案输出的顺序。</li>
</ul>
<div><div>Related Topics</div><div><li>哈希表</li><li>字符串</li><li>排序</li></div></div>\n<div><li>👍 66</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long