The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this: (You could want to display T His pattern in a fixed font for better legibility)
P A H N
A P L S i i G
Y I R
And then read line: "Pahnaplsiigyir"
Write the code that would take a string and make this conversion given a number of rows:
String Convert (string s, int numrows);
Example 1:
input:s = "Paypalishiring", NumRows = 3
Output: "Pahnaplsiigyir"
Example 2:
input:s = "Paypalishiring", NumRows = 4
Output: "Pinalsigyahrpi"
Explanation:
P I N
A L S I G
Y A H R
P I
class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ l = [‘‘ for _ in range(numRows)] if numRows == 1: return s total = 2*(numRows-1) for i in range(len(s)): pos = i % total if pos > numRows-1: pos = total - pos l[pos] += s[i] res = ‘‘ for i in range(numRows): res += l[i] return res
There is no need to initialize the entire matrix, just initialize a one-dimensional list,l[i] to save the case of line I.
6. ZigZag Conversion