Advertisement
Guest User

Grokking 237

a guest
Oct 13th, 2022
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. class Solution {
  2.     public String convert(String s, int numRows) {
  3.         if (numRows == 1) return s;
  4.        
  5.         List<StringBuilder> rows = new ArrayList<>();
  6.        
  7.         int currentRow = 0;
  8.         boolean direction = false;
  9.         for (char c : s.toCharArray()) {
  10.             if (rows.size() == currentRow) {
  11.                 rows.add(new StringBuilder());
  12.             }
  13.             rows.get(currentRow).append(c);
  14.            
  15.             if (currentRow == 0 || currentRow == numRows - 1) {
  16.                 direction = !direction;
  17.             }
  18.            
  19.             currentRow += direction ? 1 : -1;
  20.         }
  21.        
  22.         StringBuilder result = new StringBuilder();
  23.        
  24.         for (StringBuilder row : rows) {
  25.             result.append(row);
  26.         }
  27.         return result.toString();
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement