My simple JAVA solution with HashMap


  • 0
    public List<List<String>> groupStrings(String[] strings) {
    	List<List<String>> res = new ArrayList<List<String>>();
    	HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
    	for (String s : strings) {
    		String key = "";
    		for (int i = 1; i < s.length(); i++) {
    			int diff = s.charAt(i) - s.charAt(i-1);
    			if (diff < 0) diff += 26; 
    			key += diff;
    		}
    		
    		if (!map.containsKey(key)) 
    			map.put(key, new ArrayList<String>());
    		map.get(key).add(s);    		
    	}
    	
    	for (String key: map.keySet()) {
    		Collections.sort(map.get(key)); 
    		res.add(map.get(key));
    	}
    	return res;
    }

  • 0
    This post is deleted!

  • 0
    H

    Your program will run if there are two keys "111" and "1 11"(remove the blank) that is abcd and ab(b+ 11) will cast to same pattern.


Log in to reply
 

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