leetcode--Anagrams

来源:互联网 发布:单片机驱动程序 编辑:程序博客网 时间:2024/06/15 09:52

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

[java] view plain copy
  1. public class Solution {  
  2.     public List<String> anagrams(String[] strs) {  
  3.         List<String> res = new ArrayList<String>();    
  4.         HashMap<String,Integer> map = new HashMap<String,Integer>();  
  5.         for(int i=0;i<strs.length;i++){  
  6.             char[] c = strs[i].toCharArray();  
  7.             Arrays.sort(c);  
  8.             String t = new String(c);  
  9.             if(map.containsKey(t)){  
  10.                 if(!res.contains(strs[map.get(t)])){  
  11.                     res.add(strs[map.get(t)]);  
  12.                 }  
  13.                 res.add(strs[i]);  
  14.             }else{            
  15.                 map.put(t, i);  
  16.             }  
  17.         }  
  18.         return res;    
  19.     }  
  20. }  

原文链接

原创粉丝点击