"bcd" . We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase a。249.|249. Group Shifted Strings。" />

249.|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 groupStrings(String[] strings) { List result = new ArrayList(); Map> 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 list = new ArrayList(); map.put(key.toString(), list); } map.get(key.toString()).add(str); } for (String key : map.keySet()) { List list = map.get(key); result.add(list); } return result; } }

【249.|249. Group Shifted Strings】二刷
同上
public class Solution { public List groupStrings(String[] strings) { List res = new ArrayList<>(); Map> map = new HashMap<>(); for(String str : strings){ int offset = str.charAt(0) - 'a'; StringBuilder key = new StringBuilder(); for(int i=0; i val = new ArrayList<>(); map.put(key.toString(), val); } map.get(key.toString()).add(str); } for (Map.Entry> entry : map.entrySet()){ res.add(entry.getValue()); } return res; } }

    推荐阅读