My easy understanding java solution


  • 1
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> res = new ArrayList<List<String>>();
            if(strings == null || strings.length == 0) {
                return res;
            }
            HashMap<Integer,List<List<String>>> map = new HashMap<Integer,List<List<String>>>();
            for(String s : strings) {
                boolean tag = false;
                int len = s.length();
                if(map.containsKey(len)) {
                    List<List<String>> temp = map.get(len);
                    for(int i = 0 ; i < temp.size() ; i++) {
                        List<String> t = temp.get(i);
                        String word = t.get(0);
                        if(issame(s , word)) {
                            t.add(s);
                            tag = true;
                        }
                    }
                    if(!tag) {
                        List<String> t = new ArrayList<String>();
                        t.add(s);
                        temp.add(t);
                    }
                }else {
                    List<List<String>> temp = new ArrayList<List<String>>();
                    List<String> t = new ArrayList<String>();
                    t.add(s);
                    temp.add(t);
                    map.put(len , temp);
                }
            }
            for(List<List<String>> val : map.values()) {
                res.addAll(val);
            }
            return res;
        }
        
        protected boolean issame(String s1 , String s2) {
            int sub = s1.charAt(0) - s2.charAt(0);
            if(sub < 0) {
                sub = 26 + sub;
            }
            for(int i = 1 ; i < s1.length() ; i++) {
                int len = s1.charAt(i) - s2.charAt(i);
                if(len < 0) {
                    len = 26 + len;
                }
                if(len != sub) {
                    return false;
                }
            }
            return true;
        }
    }

Log in to reply
 

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