-
Notifications
You must be signed in to change notification settings - Fork 0
/
6. ZigZag Conversion.py
58 lines (45 loc) · 1.29 KB
/
6. ZigZag Conversion.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
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length = len(s)
if length < numRows - 2: return s
pattern = []
for x in range(numRows):
pattern.append(x)
for x_con in range(numRows - 2, 0, -1):
pattern.append(x_con)
cycle = len(pattern) #8
zigzag = [''] * numRows
for iterate in range(length):
row = pattern[iterate % cycle]
text = s[iterate]
zigzag[row] += text
return ''.join(zigzag)
def convert2(self, s, numRows):
if numRows <= 1:
return s
stack = [''] * numRows
row = 0
reverse = True
for c in s:
stack[row] += c
if reverse:
if row == numRows - 1:
reverse = False
row -= 1
else:
row += 1
else:
if row == 0:
reverse = True
row += 1
else:
row -= 1
return ''.join(stack)
str = 'helloworld'
s = Solution()
s.convert(str, 5)