Leetcode题解中级篇之数组和字符串(3)字谜分组

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/29/array-and-strings/77/

题目描述:

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。  
     

思路:哎呦,这题我知道思路,但是没去写。查了下别人的思路和代码,和我想的差不多。主要还是不熟悉 字符串,字符数组,字符串数组这些转换还有Hashmap的操作。觉得好麻烦。 解决方法大概如下:先将每个字符串取出 转换为字符数组ch[]然后排序。排序完放hashmap<tmp,List<string>>中,如果已经存在相同键值key,那么在List中加入该字符串。如果不存在,新建一个列表,把该字符串加入到list中,在用temp做Key。最后将hashmap中的值都添加到大列表中List<list<string>> 返回 即可。

代码:


public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> list = new ArrayList<List<String>>();
        int len = strs.length;
        if(len<1) return list;
        Map<String,List<String>> map = new HashMap<String,List<String>>();
        String tmp = "";
        for(int i=0;i<len;i++){
        	tmp = strs[i];
        	char[] arrayOfString = tmp.toCharArray();
        	Arrays.sort(arrayOfString);
        	tmp = new String(arrayOfString);
        	if(map.containsKey(tmp)){
        		map.get(tmp).add(strs[i]);
        	}else{
        		List<String> item = new ArrayList<String>();
        		item.add(strs[i]);
        		map.put(tmp, item);
        	}
        }
        for (List<String> value : map.values()) {         	  
            list.add(value);           
        } 
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84841804