Tuesday, August 30, 2016

LeetCode Online Judge-6. ZigZag Conversion

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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

//Java Program: ZigZag Conversion
public class Solution {
    public String convert(String s, int numRows) {
        if (numRows==1) {
            return s;
        }
        char[] r = new char[s.length()];
char[][] c = new char[numRows][(s.length()/(2*numRows-2)+1)*(numRows-1)];
for(int i=0;i<s.length();++i) {
if (i%(2*numRows-2)<numRows) {
c[i%(2*numRows-2)][i/(2*numRows-2)*(numRows-1)] = s.charAt(i);
} else {
c[2*numRows-2-i%(2*numRows-2)][i/(2*numRows-2)*(numRows-1)+i%(2*numRows-2)-numRows+1] = s.charAt(i);
}
}
for(int k=0,i=0;i<c.length;++i) {
for(int j=0;j<c[0].length;++j) {
if (c[i][j]!='\u0000') {
r[k++] = c[i][j]; 
}
}
}
return String.valueOf(r);
    }
}

Android Studio Project: Classic Minesweeper Game Updated

The new version of Minesweeper repairs the problem that timing doesn't restart in some cases.

Click To Download On Amazon Appstore

Project site are in my previous post: Android Studio Project: Classic Minesweeper Game.