每日一题:面试题 10.02. 变位词组

解题思路

将每个字符串单独排序,如果构成的字符是相同的,那么排序结果也一定是相同的
利用Hash表判断这个字符串有没有出现过,如果没有出现就put排序后的字符串和对应ans中的index
利用一个index记录其在ans中的下标,利用此下标更新

代码

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String,Integer> map = new HashMap<>();//存的是返回list中对应的索引
        List<List<String>> ans = new ArrayList<>();
        int n=strs.length,index = 0;
        for (int i=0;i<n;i++){
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);//对字符串排序
            if (!map.containsKey(new String(chars))){//map中包含此字符串
                map.put(new String(chars),index);
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                ans.add(list);
                index++;
            }
            else {
                ans.get(map.get(new String(chars))).add(strs[i]);
            }
        }
        return ans;
    }
}
上一篇:LeetCode 678. 有效的括号字符串


下一篇:力扣刷题笔记 剑指Offer 05