Share my java solution using hashmap which only store string and it first place.


  • 0
    W

    My solution is easy. hash map only contains string and it first appear place. There are only three cases.

    If map contains string
    -----if value is not -1 ->then we add this string and the first appear string.
    -----else -> we only add this string because first appear string is already added.

    else -> add this string and its location into map

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

  • 0
    O

    this is wrong..
    ["abcd", "abdc", "cbad"] and your output will only be ["abcd", "abdc"]


  • 0
    W

    Hi, I tried your example on my laptop and it fine, I have output ["abcd", "abdc", "cbad"].
    If the map contains the string, it will be put into result. So cbad will be put to result.


Log in to reply
 

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