Skip to content

Latest commit

 

History

History
46 lines (44 loc) · 1.35 KB

6. ZigZag Conversion.md

File metadata and controls

46 lines (44 loc) · 1.35 KB

6. ZigZag Conversion (Medium)

[tag] string, zigzag

  • use for loop if there is a fixed increment.
'''
0 P     I    N
1 A   L S  I G
2 Y A   H R
3 P     I
from P to I takes 6 jumps. (numRows - 1) * 2
from A to S is same 
from A to L: (numRows - 1- row) * 2 
from Y to A: (numRows - 1- row) * 2

'''
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        # if numRows >= len(s):
        #     return s
        ans = ''
        for row in range(numRows):
            increment = (numRows - 1) * 2
            for i in range(row, len(s), increment):
                # for first and each downared position cols
                ans += s[i]
                if row != 0 and row != numRows - 1:
                    i_new = i + increment - 2 * row
                    if i_new < len(s):
                        ans += s[i_new]
''' While loop method
#         for row in range(numRows):
#             i = row # starting letter for each row
#             while i < len(s):
#                 ans += s[i]
#                 if row != 0 and row != numRows - 1:
#                     new_i = i + (numRows - 1 - row) * 2   
#                     if new_i < len(s):
#                         ans +=s[new_i]
                
#                 new_i = i + (numRows - 1) * 2
#                 i = new_i
'''
        return ans