Share my 5ms JAVA solution


  • 0
    P
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            if(strings == null || strings.length == 0){
                return new ArrayList<List<String>>();
            }
            HashMap< String, List<String>> map = new HashMap<>();
            Arrays.sort(strings);
            for(int i = 0; i < strings.length; i++){
                if (strings[i] == null || strings[i].length() == 0){
                    continue;
                }
                String afterChange = change(strings[i]);
                if(!map.containsKey(afterChange)){
                    List<String> list = new ArrayList<>();
                    list.add(strings[i]);
                    map.put(afterChange,list);
                }else{
                    map.get(afterChange).add(strings[i]);
                }
            }
            return new ArrayList<List<String>> (map.values());
        }
        public String change(String source){
            // not null or empy
            StringBuilder target = new StringBuilder();
            int inteval = source.charAt(0) - 'a';
            target.append('a');
            for(int i = 1; i < source.length(); i++){
                int temp = (source.charAt(i) - 'a' + 26 - inteval ) % 26;
                char c = (char) ('a' + temp);
                target.append(c);
            }
            return target.toString();
        }
    }

Log in to reply
 

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