原题链接在这里:https://leetcode.com/problems/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"]
,
A solution is:
[ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ]
题解:
维护一个HashMap, key是每个string 的 base型.
Note: char c, c - diff, need cast.
Time Complexity: O(nm), n = strings.length. m = average length of strings.
Space: O(hm.size()), HashMap size.
AC Java:
1 class Solution { 2 public List<List<String>> groupStrings(String[] strings) { 3 List<List<String>> res = new ArrayList<>(); 4 if(strings == null || strings.length == 0){ 5 return res; 6 } 7 8 Map<String, List<String>> hm = new HashMap<>(); 9 for(String s : strings){ 10 String base = getBase(s); 11 hm.putIfAbsent(base, new ArrayList<String>()); 12 hm.get(base).add(s); 13 } 14 15 return new ArrayList<List<String>>(hm.values()); 16 } 17 18 private String getBase(String s){ 19 if(s == null || s.length() == 0){ 20 return s; 21 } 22 23 char [] arr = s.toCharArray(); 24 int diff = arr[0] - 'a'; 25 for(int i = 0; i<arr.length; i++){ 26 arr[i] = (char)(arr[i]-diff); 27 if(arr[i] < 'a'){ 28 arr[i] += 26; 29 } 30 } 31 32 return new String(arr); 33 } 34 }