|
| 1 | +// https://leetcode.com/problems/zigzag-conversion/ |
| 2 | +public final class ZigZagConversion { |
| 3 | + enum Direction { |
| 4 | + SOUTH, |
| 5 | + DIAGONAL |
| 6 | + } |
| 7 | + |
| 8 | + /** |
| 9 | + * Apply zigzag conversion: |
| 10 | + * PAYPALISHIRING -> PAHNAPLSIIGYIR |
| 11 | + * |
| 12 | + * Here are the things I'm thinking of. |
| 13 | + * |
| 14 | + * numRows = column size |
| 15 | + * numRows-2 = diagonal size |
| 16 | + * |
| 17 | + * So we want to understand how long the string is. Then we want |
| 18 | + * to go as follows: |
| 19 | + * |
| 20 | + * - Grab numRows chars |
| 21 | + * - Append to a mapping where key = rawIndex, value = list of chars |
| 22 | + * - Grab numRows-2 |
| 23 | + * - Append to a mapping where key = rawIndex-1, value = list of chars |
| 24 | + * - If at any point we run out of characters, we stop the iteration |
| 25 | + */ |
| 26 | + public String convert(String s, int numRows) { |
| 27 | + StringBuilder result = new StringBuilder(); |
| 28 | + |
| 29 | + // Initialize the mapping |
| 30 | + StringBuilder[] allRows = new StringBuilder[numRows]; |
| 31 | + for (int i = 0; i < numRows; i++) { |
| 32 | + allRows[i] = new StringBuilder(); |
| 33 | + } |
| 34 | + |
| 35 | + // Build the mapping |
| 36 | + helper(s, numRows, allRows, Direction.SOUTH, 0); |
| 37 | + |
| 38 | + // Join the mapping strings together |
| 39 | + for (int depth = 0; depth < numRows; depth++) { |
| 40 | + result.append(allRows[depth].toString()); |
| 41 | + } |
| 42 | + |
| 43 | + return result.toString(); |
| 44 | + } |
| 45 | + |
| 46 | + public void helper( |
| 47 | + String s, |
| 48 | + int numRows, |
| 49 | + StringBuilder[] allRows, |
| 50 | + Direction direction, |
| 51 | + int absoluteIndex |
| 52 | + ) { |
| 53 | + int iterations = (direction == Direction.SOUTH) |
| 54 | + ? numRows : numRows - 2; |
| 55 | + |
| 56 | + for (int i = 0; i < iterations; i++) { |
| 57 | + if (absoluteIndex == s.length()) { |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + int depth = (direction == Direction.SOUTH) |
| 62 | + ? i : iterations - i; |
| 63 | + |
| 64 | + allRows[depth].append(s.charAt(absoluteIndex)); |
| 65 | + |
| 66 | + absoluteIndex++; |
| 67 | + } |
| 68 | + |
| 69 | + Direction nextDirection = (direction == Direction.SOUTH) |
| 70 | + ? Direction.DIAGONAL : Direction.SOUTH; |
| 71 | + |
| 72 | + helper(s, numRows, allRows, nextDirection, absoluteIndex); |
| 73 | + } |
| 74 | +} |
0 commit comments