JAVA solution using Sort and hashCode.


  • 1
    F
    public class Solution {
        
        public List<String> anagrams(String[] strs) {
            Map<Integer, String> map = new HashMap<Integer, String>();
            Set<String> set = new HashSet<String>();
            List<String> result = new LinkedList<String>();
            
            if(strs.length == 0 || strs.length == 1)
                return result;
            for(String s : strs){
                char[] c = s.toCharArray();
                Arrays.sort(c);
                String cur = new String(c);
                if(map.containsKey(cur.hashCode())){
                    if(!set.contains(cur)){
                        result.add(s);
                        set.add(cur);
                        result.add(map.get(cur.hashCode()));
                        continue;
                    }
                    result.add(s);
                    continue;
                }
                map.put(cur.hashCode(), s);
            }
            return result;       
        }
    }

  • 0
    D

    Thanks for this:

            char[] c = s.toCharArray();
            Arrays.sort(c);
            String cur = new String(c);

Log in to reply
 

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