[抄题]:
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.
Example:
Input:["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
为了保证ba和az分为同一类,加上循环总数26
[思维问题]:
不知道怎么处理相对顺序:就多设置一个变量,来记录总共的相对偏移量就行了
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 数据类型:key要求是string,但是计算出来的是数字,所以还是要加“”转一下
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
不知道怎么处理相对顺序:就多设置一个变量,来记录总共的相对偏移量就行了
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution {
public List<List<String>> groupStrings(String[] strings) {
//initialization: result, map
List<List<String>> result = new ArrayList<List<String>>();
HashMap<String, List<String>> map = new HashMap<>(); //add (key, list) to map
for (String string : strings) {
String key = "";
for (int i = 1; i < string.length(); i++) {
int diff = string.charAt(i) - string.charAt(i - 1);
key += diff > 0 ? diff : 26 + diff;
}
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(string);
} //sort and output the results
for (List<String> ss : map.values()) {
Collections.sort(ss);
result.add(ss);
} //return
return result;
} /*
az 25 - 0 = 25
ba -1 + 26 = 25
*/
}