LeetCode: Z-shaped transformation

Problem Description: Arrange a given character string in a zigzag pattern from top to bottom and from left to right according to the given number of lines. (Input string s and number of rows numRows, output in new order)

For example, when the input string is "LEETCODEISHIRING" and the number of rows is 3, the arrangement is as follows:

L   C   I   R
E T O E S I I G
E   D   H   N

Method one: find the law

1. Modularity
We can see from the form of the above example that because these Z are overlapping, we can think of "one vertical" plus "one mention" as a small module, such as "LEET" as the first Small module, use "CODE" as the second small module ...

2. Determine the size of the module
First, find a more representative example:

L	  D     R
E   O E   I I
E C	  I H   N
T     S     G

We can conclude that a small module "pricked" is better than "mention" more than two characters, and the number of characters "pricked" is the number of lines it can be deduced therefrom numRows small module size:
batch_z = 2 * numRows-2

3. Determine the output relationship If
you output by line (take the second example as an example),
the 0, 1, 2, and 3 elements of line 0 have 0% 6 = 0, 6% 6 = 0, 12% 6 = 0, 18% 6 = 0
Line 1, line 1, 1, 2, 3 elements have 1% 6 = 1,7% 6 = 1,13% 6 = 1,19% 6 = 1
···
The output order can be derived from this
4. Procedure

class Solution:
    def convert(self, s: str, numRows: int) -> str:
    	new_s = []
    	if numRows == 0:
    		return None
    	elif numRows == 1:
    		return s
    	batch_z = 2*numRows-2  #一条竖边和一条斜边构成一个z
    	vertical_z = int((batch_z+2)/2)   # 竖边的长度
    	oblique_z = batch_z-vertical_z  #斜边的长度

    	for j in range(0,vertical_z):
    		for i in range(0,len(s)):
    			if i%batch_z == j or i%batch_z == batch_z-j:
    				new_s.append(s[i])

    	new_s = ''.join(new_s)  # 将列表里的元素放在一个字符串里面
    	return new_s

if __name__ == '__main__':
	solution1 = Solution()
	s = "12345678"
	#s = "abcdefghi"
	#s = "a"
	print("s=",s)
	numRows = 1
	new_s = solution1.convert(s,numRows)
	print(new_s)
Published 41 original articles · praised 13 · visits 6692

Guess you like

Origin blog.csdn.net/comli_cn/article/details/104822316