Home LeetCode. 6. ZigZag Conversion
Post
Cancel

LeetCode. 6. ZigZag Conversion

ZigZag Conversion

image

[Link] https://leetcode.com/problems/zigzag-conversion/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.*;

class Solution {
    public String convert(String s, int numRows) {
        if(numRows == 1) return s;
        StringBuilder sb = new StringBuilder();
        ArrayList<StringBuilder> al = new ArrayList<> ();
        int inc = 1;
        int h = 0;
        for(int i = 0; i < numRows; i++) {
            StringBuilder sb2 = new StringBuilder ();
            al.add(sb2);
        }
        for(int i = 0; i < s.length(); i++) {
            StringBuilder sb2 = al.get(h);
            sb2.append(s.charAt(i));
            h+=inc;
            if(h == numRows - 1) inc = -1;
            else if(h == 0) inc = 1;
        }
        for(int i = 0; i < numRows; i++) {
            sb.append(al.get(i));
        }
        return sb.toString();
    }
}
This post is licensed under CC BY 4.0 by the author.