|
5 | 5 | import java.util.HashMap;
|
6 | 6 | import java.util.List;
|
7 | 7 | import java.util.Map;
|
8 |
| -/**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: |
9 | 8 |
|
10 |
| - "abc" -> "bcd" -> ... -> "xyz" |
11 |
| - Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. |
12 |
| -
|
13 |
| - For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], |
14 |
| - A solution is: |
15 |
| -
|
16 |
| - [ |
17 |
| - ["abc","bcd","xyz"], |
18 |
| - ["az","ba"], |
19 |
| - ["acef"], |
20 |
| - ["a","z"] |
21 |
| - ] |
22 |
| -
|
23 |
| - */ |
24 | 9 | public class _249 {
|
25 | 10 |
|
26 |
| - public List<List<String>> groupStrings(String[] strings) { |
| 11 | + public static class Solution1 { |
| 12 | + public List<List<String>> groupStrings(String[] strings) { |
| 13 | + |
| 14 | + List<List<String>> result = new ArrayList<List<String>>(); |
| 15 | + Map<String, List<String>> map = new HashMap<String, List<String>>(); |
27 | 16 |
|
28 |
| - List<List<String>> result = new ArrayList<List<String>>(); |
29 |
| - Map<String, List<String>> map = new HashMap<String, List<String>>(); |
| 17 | + for (String word : strings) { |
| 18 | + String key = ""; |
| 19 | + int offset = word.charAt(0) - 'a'; |
| 20 | + for (int i = 1; i < word.length(); i++) { |
| 21 | + key += (word.charAt(i) - offset + 26) % 26; |
| 22 | + } |
30 | 23 |
|
31 |
| - for (String word : strings) { |
32 |
| - String key = ""; |
33 |
| - int offset = word.charAt(0) - 'a'; |
34 |
| - for (int i = 1; i < word.length(); i++) { |
35 |
| - key += (word.charAt(i) - offset + 26) % 26; |
| 24 | + if (!map.containsKey(key)) { |
| 25 | + map.put(key, new ArrayList<>()); |
| 26 | + } |
| 27 | + map.get(key).add(word); |
36 | 28 | }
|
37 | 29 |
|
38 |
| - if (!map.containsKey(key)) { |
39 |
| - map.put(key, new ArrayList<>()); |
| 30 | + for (List<String> list : map.values()) { |
| 31 | + Collections.sort(list); |
| 32 | + result.add(list); |
40 | 33 | }
|
41 |
| - map.get(key).add(word); |
42 |
| - } |
43 | 34 |
|
44 |
| - for (List<String> list : map.values()) { |
45 |
| - Collections.sort(list); |
46 |
| - result.add(list); |
| 35 | + return result; |
47 | 36 | }
|
48 |
| - |
49 |
| - return result; |
50 |
| - |
51 | 37 | }
|
52 | 38 |
|
53 | 39 | }
|
0 commit comments