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的字符串分组。首先想到得给某一类字符串找一个标准字符串,可以都把首字母shift 到‘a’ 上,后面的字母依次shift,然后用hashmap判断有没有这个字符串生成的标准字符串,有的话在list后面加上这个字符串,没有的话,创建一个新key和对应的新list,最后返回结果。代码如下:
public class Solution {
public List<List<String>> groupStrings(String[] strings) {
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
//List<List<String>> rlist = new ArrayList<List<String>>();
for(String str:strings) {
int offset = str.charAt(0) - 'a';
String temp = "";
for (char ch:str.toCharArray()) {
if (ch - offset < 'a') {
temp += (ch - offset + 26);
} else {
temp += (ch - offset);
}
}
if (!hm.containsKey(temp)) {
hm.put(temp, new ArrayList<String>());
}
hm.get(temp).add(str);
}
/*for (String key:hm.keySet()) {
List<String> templist = hm.get(key);
Collections.sort(templist);
rlist.add(templist);
}*/
//上面一大段可以用下面这一句代替
return new ArrayList<List<String>>(hm.values());
}
}
标准字符串的生成方法也可以采用后一个字母和前一个字母的差,代码如下:
public List<List<String>> groupStrings(String[] strs) {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
Arrays.sort(strs);
for (String s : strs) {
String key = "";
for (int i = 1; i < s.length(); i++)
key += String.format("%2d", (s.charAt(i) - s.charAt(i-1) + 26) % 26);//Difference from the previous char.
if (!map.containsKey(key)) map.put(key, new ArrayList<String>());
map.get(key).add(s);
}
return new ArrayList<List<String>>(map.values());
}