Advertisement
1988coder

6. ZigZag Conversion

Oct 14th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. class Solution {
  2.     public String convert(String s, int numRows) {
  3.         if (s == null || numRows == 1 || s.length() <= numRows) {
  4.             return s;
  5.         }
  6.        
  7.         StringBuilder result = new StringBuilder();
  8.        
  9.         for (int row = 0; row < numRows; row++) {
  10.             int step1 = (numRows - row - 1) * 2;
  11.             int step2 = row * 2;
  12.             int pos = row;
  13.             result.append(s.charAt(pos));
  14.            
  15.             while (true) {
  16.                 pos += step1;
  17.                 if (pos >= s.length()) {
  18.                     break;
  19.                 }
  20.                 if (step1 > 0) {
  21.                     result.append(s.charAt(pos));
  22.                 }
  23.                 pos += step2;
  24.                 if (pos >= s.length()) {
  25.                     break;
  26.                 }
  27.                 if (step2 > 0) {
  28.                     result.append(s.charAt(pos));
  29.                 }
  30.             }
  31.         }
  32.        
  33.         return result.toString();
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement