Advertisement
Guest User

Zigzag - ChatGPT

a guest
Feb 16th, 2024
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | Source Code | 0 0
  1. class Solution(object):
  2.    def convert(self, s, numRows):
  3.        """
  4.       :type s: str
  5.       :type numRows: int
  6.       :rtype: str
  7.       """
  8.     if numRows == 1 or numRows >= len(s):
  9.            return s
  10.  
  11.        # Create a list of strings to store characters in each row
  12.        rows = [''] * numRows
  13.      
  14.        # Initialize variables for tracking the current row and direction
  15.        current_row = 0
  16.        direction = 1
  17.      
  18.        # Iterate through each character in the string
  19.        for char in s:
  20.            # Append the character to the current row
  21.            rows[current_row] += char
  22.          
  23.            # Update the current row and direction
  24.            current_row += direction
  25.          
  26.            # Change direction when reaching the top or bottom row
  27.            if current_row == 0 or current_row == numRows - 1:
  28.                direction *= -1
  29.      
  30.        # Concatenate rows to form the zigzag pattern
  31.        return ''.join(rows)
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement