[leetcode] No 6. Zigzag Conversion Python
[Problem]
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)
[Explanation]
After arranging string to zigzag, combine zigzagged string as one.
There is a given number of rows. So I can arrange string in codition of rows and combine as one
For example, 'PAYPALISHIRING' and a given rows is 3
row 1. P A H N > (rearrange) > PAHN
row 2. A P L S I I G > > APLSIIG
row 3. Y I R > > YIR
>>> (combine) >>>> PAHNAPLSIIGYIR (It is correct answer!)
[Solution]
1. First, string has to rearrange as zigzag. There are directions such as up and down.
So, I consider direction as defined 'd'.
2. In each row, an arranged character has to be combined with a previous character.
In this part, I have to consider the location of row, 'rows'.
If the initial row allocation is empty, 'append' is used.
If not, I just add a new character to the previous string located to the specifc row.
3. If a direction is down, 'rows' is increased by 1.
On the other hands, a direction is up, 'rows' is decreased by 1.
If 'rows' is approched to the limited number like 0 or a number of row, it has to be controled as limited range.
Like, 'rows = min(max(0, rows), numRows-1)'
4. Finally, all the rearranged string which are in each row have to be combined.
class Solution: def convert(self, s: str, numRows: int) -> str: word = [] rows = 0 d = 1 for i in range(len(s)): if len(word) < numRows: word.append(s[i]) else: word[rows] = word[rows] + s[i] if d == 1: rows += 1 else: rows -= 1 if rows == numRows: rows = numRows - 2 d = 0 elif rows == -1: rows = 1 d = 1 rows = min(max(0, rows), numRows-1) ans = '' for j in range(min(len(s),numRows)): ans = ans + word[j] return ans |