Convert a string to zigzag pattern on a given number of rows and read it row by row. The string is written in a zigzag pattern across the specified number of rows, then read line by line.
For example, "PAYPALISHIRING" with 3 rows becomes:
P A H N
A P L S I I G
Y I R
Reading row by row gives "PAHNAPLSIIGYIR".
Simulate the zigzag by tracking the current row and direction. Move down until hitting the last row, then move up until hitting the first row. Append each character to the appropriate row's buffer.
Example Input & Output
Example 1
Input
"AB",1
Output
"AB"
Explanation
1 row is identity
Example 2
Input
"A",1
Output
"A"
Explanation
Single row
Example 3
Input
"",3
Output
""
Explanation
Empty
Example 4
Input
"PAYPALISHIRING",3
Output
"PAHNAPLSIIGYIR"
Explanation
Zigzag with 3 rows
Example 5
Input
"PAYPALISHIRING",4
Output
"PINALSIGYAHRPI"
Explanation
Zigzag with 4 rows
Algorithm Flow

Recommendation Algorithm Flow for Zigzag Conversion
Solution Approach
Best Answers
java
class Solution {
public String solution(String s, int n) {
if(n==1||n>=s.length())return s;
StringBuilder[] rows=new StringBuilder[n];
for(int i=0;i<n;i++)rows[i]=new StringBuilder();
int cur=0;boolean d=false;
for(int i=0;i<s.length();i++){
rows[cur].append(s.charAt(i));
if(cur==0||cur==n-1)d=!d;
cur+=d?1:-1;
}StringBuilder r=new StringBuilder();
for(StringBuilder sb:rows)r.append(sb);
return r.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
