Skip to content

Commit aa7acaf

Browse files
committed
ZigZag Conversion
1 parent ed15969 commit aa7acaf

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

LeetCode/ZigZagConversion.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
3+
4+
P A H N
5+
A P L S I I G
6+
Y I R
7+
And then read line by line: "PAHNAPLSIIGYIR"
8+
Write the code that will take a string and make this conversion given a number of rows:
9+
10+
string convert(string text, int nRows);
11+
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
12+
'''
13+
class Solution(object):
14+
def convert(self, s, numRows):
15+
if numRows == 1:
16+
return s
17+
18+
n = 2*numRows-2
19+
result = ''
20+
l = len(s)
21+
22+
# the first row
23+
for i in xrange(0, l, n):
24+
result += s[i]
25+
26+
# rows in between
27+
for i in xrange(1,numRows-1):
28+
j = i
29+
while j < l+i-(n-i):
30+
result += s[j]
31+
result += s[j+(n-i)-i]
32+
j += n
33+
# if the number of chars in this row is odd
34+
if j < l:
35+
result += s[j]
36+
37+
# the last row
38+
for i in xrange(numRows - 1, l, n):
39+
result += s[i]
40+
41+
return result

0 commit comments

Comments
 (0)