forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecrypt-string-from-alphabet-to-integer-mapping.py
64 lines (55 loc) · 1.35 KB
/
decrypt-string-from-alphabet-to-integer-mapping.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Time: O(n)
# Space: O(1)
# forward solution
class Solution(object):
def freqAlphabets(self, s):
"""
:type s: str
:rtype: str
"""
def alpha(num):
return chr(ord('a') + int(num)-1)
i = 0
result = []
while i < len(s):
if i+2 < len(s) and s[i+2] == '#':
result.append(alpha(s[i:i+2]))
i += 3
else:
result.append(alpha(s[i]))
i += 1
return "".join(result)
# Time: O(n)
# Space: O(1)
# backward solution
class Solution2(object):
def freqAlphabets(self, s):
"""
:type s: str
:rtype: str
"""
def alpha(num):
return chr(ord('a') + int(num)-1)
i = len(s)-1
result = []
while i >= 0:
if s[i] == '#':
result.append(alpha(s[i-2:i]))
i -= 3
else:
result.append(alpha(s[i]))
i -= 1
return "".join(reversed(result))
# Time: O(n)
# Space: O(1)
import re
# regex solution
class Solution3(object):
def freqAlphabets(self, s):
"""
:type s: str
:rtype: str
"""
def alpha(num):
return chr(ord('a') + int(num)-1)
return "".join(alpha(i[:2]) for i in re.findall(r"\d\d#|\d", s))