249. 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"],
A solution is:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

一刷
题解:
就是问,哪些字符串属于同一个shift group.
首先,对于一个字符串,里面的每个字符减去第一个字符形成一个新的字符串。构成同一个新字符串的字符串属于同一个sequence

public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> result = new ArrayList<List<String>>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strings) {
            int offset = str.charAt(0) - 'a';
            StringBuilder key = new StringBuilder();
            for (int i = 0; i < str.length(); i++) {
                char c = (char) (str.charAt(i) - offset);
                if (c < 'a') {
                    c += 26;
                }
                key.append(c);
            }
            if (!map.containsKey(key.toString())) {
                List<String> list = new ArrayList<String>();
                map.put(key.toString(), list);
            }
            map.get(key.toString()).add(str);
        }
        for (String key : map.keySet()) {
            List<String> list = map.get(key);
            result.add(list);
        }
        return result;
    }
}

二刷
同上

public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> res = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();
        for(String str : strings){
            int offset = str.charAt(0) - 'a';
            StringBuilder key = new StringBuilder();
            for(int i=0; i<str.length(); i++){
                char c = (char)(str.charAt(i) - offset);
                if(c<'a') c+=26;
                key.append(c);
            }
            if(!map.containsKey(key.toString())){
                List<String> val = new ArrayList<>();
                map.put(key.toString(), val);
            }
            map.get(key.toString()).add(str);
        }
        for (Map.Entry<String, List<String>> entry : map.entrySet()){
            res.add(entry.getValue());
        }
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容