BiruLyu
6/13/2017 - 4:39 PM

249. Group Shifted Strings.java

public class Solution {
    private String getSequence(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < str.length(); i++) {
            int temp = str.charAt(i) - str.charAt(i - 1);
            if (temp > 0) {
                temp -= 26;
            }
            sb.append(temp);
        }
        return sb.toString();
    }
    public List<List<String>> groupStrings(String[] strings) {
        HashMap<String, List<String>> map = new HashMap<String,List<String>>();
        List<List<String>> res = new ArrayList<List<String>>();
        for (String str : strings) {
            String key = getSequence(str);
            if(!map.containsKey(key)) {
                map.put(key, new ArrayList<String>());
            }
            map.get(key).add(str);
        }
        for(String key : map.keySet()) {
            res.add(map.get(key));
        }
        return res;
    }
}

/*
["abc","bcd","acef","xyz","az","ba","a","z"]
["az","ba","bz","ac","ca","cz","ad","zc"]
[]
*/