当前位置:网站首页>Leetcode t49: grouping of alphabetic words

Leetcode t49: grouping of alphabetic words

2022-07-04 14:24:00 Fan Qianzhi

Title Description

Here's an array of strings , Would you please Letter heterotopic word Put together . You can return a list of results in any order .

Letter heterotopic word Is a new word obtained by rearranging the letters of the source word , Letters in all source words are usually used just once .

Example 1:

Input : strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
Output : [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]

Example 2:

Input : strs = [“”]
Output : [[“”]]

Example 3:

Input : strs = [“a”]
Output : [[“a”]]

Tips :

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] Only lowercase letters

Ideas

If two strings are sorted according to characters , The resulting strings are equal , Then these two strings are alphabetic ectopic words .
Use HashMap, Improve access efficiency .

Code

	Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
	
    public List<List<String>> groupAnagrams(String[] strs) {
    
    	for(int i = 0; i < strs.length; i++) {
    
    		char[] chs = strs[i].toCharArray();
    		Arrays.sort(chs);
    		if(map.containsKey(new String(chs))) {
    
    			map.get(new String(chs)).add(i);
    		} else {
    
    			List<Integer> lis = new ArrayList<Integer>();
    			lis.add(i);
    			map.put(new String(chs), lis);
    		}
    	}
    	List<List<String>> res = new ArrayList<List<String>>();
    	for(List<Integer> lis: map.values()) {
    
    		List<String> tmp = new ArrayList<String>();
    		for(int ind: lis) tmp.add(strs[ind]);
    		res.add(tmp);
    	}
    	return res;
    }
原网站

版权声明
本文为[Fan Qianzhi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041222044192.html