Shared my 400ms java solution


  • 0
    Y

    this problem aim to find the anagrams, so there are one anagram are repeated, so my thinking is to sort the string and put in hashmap, if it is the same after sorting, it means it is the result,

    public class Solution {
        public String sort(String string)
    	{
    		char[] array = string.toCharArray();
    		Arrays.sort(array);
    		return new String(array);
    	}
    		
        public List<String> anagrams(String[] strs) {
            List<String> res = new ArrayList<String>();
    		if(strs == null && strs.length == 0)
    			return res;
            Map<String, Integer> map = new HashMap<String, Integer>();
            String temp = "";
            int id = 0;
            for(int i = 0; i< strs.length; i++)
            {
            	temp = sort(strs[i]);
            	if(!map.containsKey(temp))
            		map.put(temp, i);
            	else{
            		id = map.get(temp);
            		if(id != -1)
            		{
            			res.add(strs[id]);
            		}
            		res.add(strs[i]);
            		map.put(temp, -1);
            	}
            }
            return res;
        }
    }

Log in to reply
 

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