My solution in Java(hashing the input)


  • 0
    public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> ret = new ArrayList<List<String>>();
            if(strings == null || strings.length == 0) return ret;
            
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            for(int i = 0; i < strings.length; i ++){
                String str = transfer(strings[i]);
                int index = 0;
                if(map.containsKey(str)){
                    index = map.get(str);
                }else{
                    index = ret.size();
                    map.put(str, index);
                }
                if(ret.size() >= index + 1){
                    ret.get(index).add(strings[i]);
                }else{
                    ret.add(new ArrayList<String>(Arrays.asList(strings[i])));
                }
            }
            return ret;
        }
        public String transfer(String str){
            StringBuilder sb = new StringBuilder();
            if(str == null) return sb.toString();
            
            int step = str.charAt(0) - 'a';
            sb.append("a");
            for(int i = 1; i < str.length(); i ++){
                char temp;
                if(str.charAt(i) - 'a' - step < 0)
                    temp = (char)(str.charAt(i) + 26 - step);
                else
                    temp = (char)(str.charAt(i) - step);
                sb.append(String.valueOf(temp));
            }
            return sb.toString();
        }
    

Log in to reply
 

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