Source of the topic:
https://leetcode.com/problems/zigzag-conversion/
Test Instructions Analysis:
This topic is the subject of string processing. Enter a string and a number, fill the string in the inverted Z-input string, and then read the character by column, and get a new character that prints the character. Example: string "Paypalishiring", 3
p< /td> |
&NBSP; |
a |
|
h |
&NBSP; |
n |
a |
p |
l |
s |
i |
i |
g |
y |
&NBSP; |
i |
&NBSP; |
r |
&NBSP; |
&NBSP; |
The new character obtained is "Pahnaplsiigyir".
Topic Ideas:
This problem is just a simple string processing. First, we can simply optimize the z-string to combine the "fold" in Z. For example: "ABCDEFGHIJKL", 4
a |
&NBSP; |
& nbsp; |
g |
&NBSP; |
&NBSP; | /tr>
b |
&NBSP; |
f |
h |
&NBSP; |
l |
c |
e |
&NBSP; |
i |
k |
&NBSP; |
tr>
d |
&NBSP; |
|
j |
&NBSP; |
< /td> |
After optimization:
It is not difficult to find that the resulting results are the same, and the number of columns in the list is reduced. In C and C + +, you can directly define a two-dimensional array, read the characters in, and then read directly. But with the Python initialization list is troublesome, I think directly through the subscript rule can be directly obtained, the first line and the last line next subscript is the previous + 2*numrows–2, while the other is First + (numrows-i) –2 + 2*i,i is the number of lines.
Code (Python):
1 classsolution (object):2 defconvert (self, S, numrows):3 """4 : Type S:str5 : Type Numrows:int6 : Rtype:str7 """8Size =Len (s)9 ifSize <= NumRowsorNumRows = = 1:Ten returns OneAns ="' Ai =0 - whileI <NumRows: -j =I the ifi = = 0ori = = NumRows-1: - whileJ <Size: -Ans + =S[j] -J + = 2*numrows-2 + if2 * NumRows-2 = =0: - Break + Else: A whileJ <Size: atAns + =S[j] -J + = (numrows-i)-2 - ifJ >=Size: - Break -Ans + =S[j] -J + =I ini + = 1 - returnAns
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4798575.html
[Leetcode] (python): 006-zigzag Conversion