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"]
]
Solution:
思路: 將strs按照規(guī)律編碼Map(code_str -> list(string)) 歸到不同類,輸出各list(string)。
區(qū)別他們不同的是str的length 和 他們?cè)谧址碇?strong>之間的相對(duì)位置汤徽,shift后也不變州叠。
相對(duì)位置可以 以 第一個(gè)字符在字符表中的位置 做參照標(biāo)準(zhǔn)(encode1) 或以 前一個(gè)字符在字符表中的位置 為參照坐標(biāo)(encode2)
Time Complexity: O(mn) Space Complexity: O(mn) 不算結(jié)果
m個(gè)str,長(zhǎng)度為n
Solution Code:
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>>();
//encode
for (String str : strings) {
String key = encode1(str);
if (!map.containsKey(key)) {
List<String> list = new ArrayList<String>();
map.put(key, list);
}
map.get(key).add(str);
}
// prepare the result
for (String key : map.keySet()) {
List<String> list = map.get(key);
// Collections.sort(list);
result.add(list);
}
return result;
}
private String encode1(String str) {
String key = "";
for (int i = 0; i < str.length(); i++) {
char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
if (c < 'a') c += 26;
key += c;
}
return key;
}
private String encode2(String str) {
String key = "";
for (int i = 0; i < str.length(); i++) {
char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
if (c < 'a') c += 26;
key += c;
}
return key;
}
}