Java Solution - Concise Explanation


  • 0
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            if (strings.length == 0) return Collections.emptyList(); 
            
            HashMap<String, List<String>> map = new HashMap<>();  
    
            for (String s : strings) {
                char[] chars = s.toCharArray(); 
                int[] nums = new int[chars.length - 1]; 
                
                for (int i = 1; i< chars.length; i++)
                    nums[i - 1] = (chars[i] - chars[i - 1] + 26) % 26; 
    
                // default value, in case only 1 char is in the string.
                String key = "-1";  
                // convert nums[] to string, as the key
                if (chars.length > 1) key = Arrays.toString(nums); 
                
                if (!map.containsKey(key)) {
                    // not in the map, then create a new list of strings
                    List<String> curr = new LinkedList<>(); 
                    curr.add(s);
                    map.put(key, curr); 
                } else {
                    // in the map, add the string to the existing list. 
                    map.get(key).add(s); 
                }
            }
            
            return new ArrayList<List<String>>(map.values());
        }
    }

Log in to reply
 

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