Leetcode - Group Shifted Strings

My code:

public class Solution {
    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, List<String>> map = new HashMap<String, List<String>>();
        for (int i = 0; i < strings.length; i++) {
            String s = strings[i];
            int offset = s.charAt(0) - 'a';
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < s.length(); j++) {
                char c = (char) (s.charAt(j) - offset);
                if (c < 'a') {
                    c = (char) (c + 26);
                }
                sb.append(c);
            }
            String shiftedStr = sb.toString();
            if (!map.containsKey(shiftedStr)) {
                map.put(shiftedStr, new ArrayList<String>());
            }
            map.get(shiftedStr).add(s);
        }
        
        for (String head : map.keySet()) {
            ret.add(map.get(head));
        }
        
        return ret;
    }
}

reference:
https://discuss.leetcode.com/topic/20722/my-concise-java-solution

这道题目也是没做出来。现在想想,思路还是很清晰的。
就是把所有的string全部转换到 ‘a’开头,然后hashtable 解决。
好久没做string,有些生疏。

Anyway, Good luck, Richardo! — 09/18/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/32a094dae504#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞