LeetCode 6 – ZigZag Conversion

Posted on December 22, 2013

Last updated on December 22, 2013

Solution to LeetCode ZigZag Conversion problem.

The idea is that that for \(n\) rows, the letters go into rows in this order: \(1, 2, 3, \ldots, n, n-1, n-2, \ldots, 1, 2, \ldots\). Simply make an array, and put each letter into the appropriate slot.

public String convert(String s, int nRows) {
  if(nRows == 1) return s;
  String[] res = new String[nRows];
  for(int i = 0; i < nRows; i++) res[i] = "";
  int ctr = 0;
  boolean flag = false;

  for(char c : s.toCharArray()){
    res[ctr] += (c + "");
    if(ctr == nRows-1 || ctr == 0) flag = !flag;
    if(flag) ctr++;
    else ctr--;
  }

  String result = "";

  for(String ss : res) result += ss;

  return result;
}
ZigZag Conversion
Markdown SHA1: 30fddb413d0e14f1a47c65f4259cd450a61a9bf6