-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupStrings.py
More file actions
37 lines (29 loc) · 1.43 KB
/
groupStrings.py
File metadata and controls
37 lines (29 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# class Solution:
# def groupStrings(self, strings: List[str]) -> List[List[str]]:
# def shift_letter(letter, shift):
# return chr((ord(letter) -shift)%26 + ord('a'))
# def do_hash(string):
# shift= ord(string[0])
# return ''.join(shift_letter(letter, shift) for letter in string)
# groups= collections.defaultdict(list)
# for string in strings:
# ret= do_hash(string)
# groups[ret]=string
# return list(groups.values())
class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
def shift_letter(letter: str, shift: int):
return chr((ord(letter) - shift) % 26 + ord('a'))
# Create a hash value
def get_hash(string: str):
# Calculate the number of shifts to make the first character to be 'a'
shift = ord(string[0])
return ''.join(shift_letter(letter, shift) for letter in string)
# Create a hash_value (hashKey) for each string and append the string
# to the list of hash values i.e. mapHashToList["abc"] = ["abc", "bcd"]
groups = collections.defaultdict(list)
for string in strings:
hash_key = get_hash(string)
groups[hash_key].append(string)
# Return a list of all of the grouped strings
return list(groups.values())