|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * 1324. Print Words Vertically |
| 8 | + * |
| 9 | + * Given a string s. Return all the words vertically in the same order in which they appear in s. |
| 10 | + * Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). |
| 11 | + * Each word would be put on only one column and that in one column there will be only one word. |
| 12 | + * |
| 13 | + * Example 1: |
| 14 | + * Input: s = "HOW ARE YOU" |
| 15 | + * Output: ["HAY","ORO","WEU"] |
| 16 | + * Explanation: Each word is printed vertically. |
| 17 | + * "HAY" |
| 18 | + * "ORO" |
| 19 | + * "WEU" |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * Input: s = "TO BE OR NOT TO BE" |
| 23 | + * Output: ["TBONTB","OEROOE"," T"] |
| 24 | + * Explanation: Trailing spaces is not allowed. |
| 25 | + * "TBONTB" |
| 26 | + * "OEROOE" |
| 27 | + * " T" |
| 28 | + * |
| 29 | + * Example 3: |
| 30 | + * Input: s = "CONTEST IS COMING" |
| 31 | + * Output: ["CIC","OSO","N M","T I","E N","S G","T"] |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * 1 <= s.length <= 200 |
| 35 | + * s contains only upper case English letters. |
| 36 | + * It's guaranteed that there is only one space between 2 words. |
| 37 | + * */ |
| 38 | +public class _1324 { |
| 39 | + public static class Solution1 { |
| 40 | + public List<String> printVertically(String s) { |
| 41 | + String[] words = s.split(" "); |
| 42 | + int columnMax = 0; |
| 43 | + for (String word : words) { |
| 44 | + columnMax = Math.max(columnMax, word.length()); |
| 45 | + } |
| 46 | + char[][] matrix = new char[words.length][columnMax]; |
| 47 | + for (int i = 0; i < words.length; i++) { |
| 48 | + int j = 0; |
| 49 | + for (; j < words[i].length(); j++) { |
| 50 | + matrix[i][j] = words[i].charAt(j); |
| 51 | + } |
| 52 | + while (j < columnMax) { |
| 53 | + matrix[i][j++] = '#'; |
| 54 | + } |
| 55 | + } |
| 56 | + List<String> result = new ArrayList<>(); |
| 57 | + for (int j = 0; j < columnMax; j++) { |
| 58 | + StringBuilder sb = new StringBuilder(); |
| 59 | + for (int i = 0; i < matrix.length; i++) { |
| 60 | + if (matrix[i][j] != '#') { |
| 61 | + sb.append(matrix[i][j]); |
| 62 | + } else { |
| 63 | + sb.append(' '); |
| 64 | + } |
| 65 | + } |
| 66 | + String str = sb.toString(); |
| 67 | + int k = str.length() - 1; |
| 68 | + while (k >= 0 && str.charAt(k) == ' ') { |
| 69 | + k--; |
| 70 | + } |
| 71 | + result.add(str.substring(0, k + 1)); |
| 72 | + sb.setLength(0); |
| 73 | + } |
| 74 | + return result; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments