Skip to main content

Command Palette

Search for a command to run...

Problem: Zigzag Conversion

Updated
•2 min read•View as Markdown
A

({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>

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)

P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR"

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

string convert(string s, int numRows);

Screenshot 2022-08-06 195818.png

```class Solution{ public static String convert(String s, int numRows) { String result = ""; int l = 0; int length = s.length(); Character[][] matric = new Character[length][numRows]; int i = 0; int j = 0;

if (length == 0 || length == 1 || length == 2 || numRows == 1) {
    return s;
}

while (l != length) {
    if (i != 0 && i % 2 == 1) {
        j = numRows - 2;
        while (j != 0 && l != length) {
            matric[i][j] = s.charAt(l);
            l++;
            j--;
        }
        i++;
    }
    if (l == length) {
        break;
    }
    matric[i][j] = s.charAt(l);
    l++;
    j++;
    if (j == numRows) {
        i++;
    }
}

i = 0;
j = 0;

while (j != numRows) {
    if (matric[i][j] != null) {
        result = result.concat(matric[i][j].toString());
    }
    i++;
    if (i == length) {
        j++;
        i = 0;
    }
    if ( result.length() == length )
        break;
}

return result;

} } ```

More from this blog

mackph's blog

40 posts