LeetCode 6. ZigZag Conversion

Description

https://leetcode.com/problems/zigzag-conversion/description/

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)

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Explanation

To solve the problem, we are going to have two concepts interval and step to find the underlying relationship between the original input string and output zigzag pattern string.

Interval indicates the distance between two vertical columns.

Step indicates the distance between middle characters and vertical columns.

Interval is 2n – 2 where n is the input number of rows and step is interval – 2i where i is the index of the row.

Then just iterate the rows and characters to build new zigzag pattern string.

Please check video tutorial to see the demonstration to solve the problem.

Video Tutorial

Java Solution

Leave a Reply

Your email address will not be published. Required fields are marked *