Java solution for General case (Using HashMap)


  • 2
    D

    Bellow is the java code for general cases which do not require the strings to be in lower-case. If you want to take a look at the implementation for lower-case strings, you can see in
    https://oj.leetcode.com/discuss/20417/how-to-optimize

    public class Solution {
        public List<String> anagrams(String[] strs) {
            List<String> results = new ArrayList<String>();
            
            HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
            String temp;
            ArrayList<String> list;
            for(String s: strs){
                temp = sort(s);
                if(!map.containsKey(temp)){
                    list = new ArrayList<String>();
                    list.add(s);
                    map.put(temp, list);
                }else {
                    list = (ArrayList<String>) map.get(temp);
                    list.add(s);
                }
            }
            
            for(ArrayList<String> l : map.values()){
                if(l.size()<2) continue;
                for(int i = 0; i<l.size(); i++)
                    results.add(l.get(i));
            }
            return results;
        }
        public String sort(String s){
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        }
    }

  • 0
    H

    Exactly like my code. But I submitted mine with doubt cause I didn't deal with duplicates. Probably we don't need to consider that?


  • 0
    F

    Hi,

    I am thinking exactly the same as you do.
    I uses some small tricks to make the code shorter and uses less memory by using less variables.

    public class Solution {
        public List<String> anagrams(String[] strs) {
            List<String> result = new ArrayList<String>();
            HashMap<String, List<String>> dic = new HashMap<String, List<String>>();
            for(String i: strs)
            {
                String tmp = sort(i);
                if(dic.containsKey(tmp))
                {
                dic.get(tmp).add(i);
                }
                else 
                {    
                    dic.put(tmp, new ArrayList<String>(Arrays.asList(i)));
                }
            }
            for(List<String> x: dic.values())
            {
                if(x.size() >= 2)
                    result.addAll(x);
            }
            return result;
        }
        
        private String sort(String x)
        {
            char[] tmp = x.toCharArray();
            Arrays.sort(tmp);
            return new String(tmp);
        }
     }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.