2015年9月10日星期四

Group Shifted Strings

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

Note: For the return value, each inner list's elements must follow the lexicographic order.

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

没有评论:

发表评论