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"]
]
把字符串按相同規(guī)則分組。 一看就懵圈, 不會(huì)呀, 么么噠。 ╰( ̄ω ̄o)
借助一個(gè)offset 把字符都降為最字符串, 如xyz,bcd 降級(jí)后為皆為abc, 顯然他們?nèi)齻€(gè)應(yīng)該在一組。 放到hashmap里存好。
public List> groupStrings(String[] strings) {
? ? ? ? HashMap> map = new HashMap<>();?
? ? ? ? for(String str : strings){
? ? ? ? ? ? int offset = str.charAt(0) - 'a';
? ? ? ? ? ? String key = "";
? ? ? ? ? ? for(int i = 0; i < str.length(); i++){
? ? ? ? ? ? ? ? char ch = (char)(str.charAt(i) - offset);
? ? ? ? ? ? ? ? if(ch < 'a'){
? ? ? ? ? ? ? ? ? ? ch += 26;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? key += ch;
? ? ? ? ? ? }
? ? ? ? ? ? if(!map.containsKey(key)){
? ? ? ? ? ? ? ? map.put(key, new ArrayList());
? ? ? ? ? ? }
? ? ? ? ? ? map.get(key).add(str);
? ? ? ? }
? ? ? ? List> ret = new ArrayList>();
? ? ? ? Setkeyset = map.keySet();
? ? ? ? for(String key: keyset){
? ? ? ? ? ? ? ?ret.add( map.get(key));
? ? ? ? }
? ? ? ? return ret;
}