forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode-the-slanted-ciphertext.py
50 lines (46 loc) · 1.3 KB
/
decode-the-slanted-ciphertext.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
# Time: O(n)
# Space: O(1)
class Solution(object):
def decodeCiphertext(self, encodedText, rows):
"""
:type encodedText: str
:type rows: int
:rtype: str
"""
cols = len(encodedText)//rows
k = len(encodedText)
for i in reversed(xrange(cols)):
for j in reversed(xrange(i, len(encodedText), cols+1)):
if encodedText[j] != ' ':
k = j
break
else:
continue
break
result = []
for i in xrange(cols):
for j in xrange(i, len(encodedText), cols+1):
result.append(encodedText[j])
if j == k:
break
else:
continue
break
return "".join(result)
# Time: O(n)
# Space: O(n)
class Solution2(object):
def decodeCiphertext(self, encodedText, rows):
"""
:type encodedText: str
:type rows: int
:rtype: str
"""
cols = len(encodedText)//rows
result = []
for i in xrange(cols):
for j in xrange(i, len(encodedText), cols+1):
result.append(encodedText[j])
while result and result[-1] == ' ':
result.pop()
return "".join(result)