2015年10月29日星期四

Group Shifted Strings leetcode

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"]
]



这个例子有点歧义, 其实就是

abc ((b - a) + 26 )% 26 = 1, ((c - b) + 26 )% 26= 1;

bcd ((c - b) + 26 )% 26= 1, ((d - c) + 26 )% 26= 1;

所以他们是一组shifted string

["eqdf", "qcpr"]。

((‘q’ - 'e') + 26) % 26 = 12, ((‘d’ - 'q') + 26) % 26 = 13, ((‘f’ - 'd') + 26) % 26 = 2

((‘c’ - 'q') + 26) % 26 = 12, ((‘p’ - 'c') + 26) % 26 = 13, ((‘r’ - 'p') + 26) % 26 = 2


所以他们也是一组

这样用一个map, key是这些数组的集合(注意中间要有空格 否则2,2 和22就会出现相同的情况)
然后value的arraylist放入所有符合的string

public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> res = new ArrayList<List<String>>();
        HashMap<String, List<String>> map = new HashMap<String, List<String>>();
        for (String s : strings) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                int l = (s.charAt(i) - s.charAt(0) + 26) % 26;
                sb.append(l + " ");
                
            }
            String str = sb.toString();
            if (!map.containsKey(str)) {
                List<String> tem = new ArrayList<String>();
                map.put(str, tem);
            }
            map.get(str).add(s);
        }
        for (String m : map.keySet()) {
            Collections.sort(map.get(m));
            res.add(map.get(m));
        }
        return res;
    }
}

没有评论:

发表评论