Leetcode: 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"], Return: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ]
Note: For the return value, each inner list's elements must follow the lexicographic order.
关键点:group all strings that belong to the same shifting sequence, 所以找到属于相同移位序列的key 很重要。因此单独写了函数shift,
写这个shift函数,我之前想的很复杂,每个String要移26个距离,看shifted string是不是一个key。其实干嘛这么复杂,指定一个相同移位序列的key,定义为第一个char为‘a’
buffer.append((c - 'a' - dist + 26) % 26 + 'a') 极容易错。将相同移位序列的Strings存入key 对应的value中,建立正确的HashMap很重要。
1 public class Solution { 2 public List<List<String>> groupStrings(String[] strings) { 3 List<List<String>> res = new ArrayList<List<String>>(); 4 if (strings==null || strings.length==0) return res; 5 HashMap<String, List<String>> map = new HashMap<String, List<String>>(); 6 for (int i=0; i<strings.length; i++) { 7 String temp = shift(strings[i]); 8 if (map.containsKey(temp)) { 9 map.get(temp).add(strings[i]); 10 } 11 12 else { 13 List<String> li= new ArrayList<String>(); 14 li.add(strings[i]); 15 map.put(temp, li); 16 } 17 18 } 19 for (List<String> each : map.values()) { 20 Collections.sort(each); 21 res.add(new ArrayList<String>(each)); 22 } 23 return res; 24 } 25 26 public String shift(String cur) { 27 StringBuffer res = new StringBuffer(); 28 int len = cur.length(); 29 int dist = cur.charAt(0) - 'a'; 30 for (int k=0; k<len; k++) { 31 //res.append((cur.charAt(k)+j>'z')? ('a'+(int)(cur.charAt(k)+j-'z')-1) : (cur.charAt(k)+j)); 32 char c = cur.charAt(k); 33 res.append((c-'a'-dist+26)%26+'a'); 34 } 35 return res.toString(); 36 } 37 }