java 6ms HashMap method


  • 0
    T
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            List<List<String>> list = new ArrayList<List<String>>();
            for(int i=0; i<strings.length; i++) {
                char[] str = strings[i].toCharArray();
                StringBuilder sb = new StringBuilder();
                for(int j=0; j<str.length-1; j++) {
                    int offset = str[j+1]-str[j];
                    sb.append(String.valueOf(offset>=0? offset : 26+offset));
                }
                String code = sb.toString();
                if(!map.containsKey(code)) {
                    map.put(code, new ArrayList<String>());
                }
                map.get(code).add(strings[i]);
            }
            for (List<String> value : map.values()) {
                list.add(value);
            }
            return list;
        }
    }
    

  • 0
    L

    Actually, you need to add the length of the string to the code to differentiate "az" and "ach"


Log in to reply
 

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