249. Group Shifted Strings
Medium
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 non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public List<List<String>> groupStrings(String[] strings) { Map<String, List<String>> groups = new HashMap<>(); for(String str : strings){ StringBuilder sb = new StringBuilder(); int diff = str.charAt(0) - 'a'; for(char c : str.toCharArray()){ sb.append((char)(c-diff>=97?c-diff:c-diff+26)); } groups.computeIfAbsent(sb.toString(), k->new ArrayList<>()).add(str); } List<List<String>> lists = new ArrayList<>(); for(List<String> list : groups.values()){ lists.add(list); } return lists; } } |
No comments:
Post a Comment