1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public List<String> printVertically(String s) { String[] words = s.split(" "); int maxLength = 0; for (String word : words) { maxLength = Math.max(maxLength, word.length()); }
List<StringBuilder> sbList = new ArrayList<>(maxLength); for (int i = 0; i < maxLength; i++) { sbList.add(new StringBuilder()); }
for (int j = 0; j < maxLength; j++) { for (int i = 0; i < words.length; i++) { if (j < words[i].length()) { sbList.get(j).append(words[i].charAt(j)); } else { sbList.get(j).append(" "); } } }
List<String> resultList = new ArrayList<>(); for (int i = 0; i < maxLength; i++) { StringBuilder sb = sbList.get(i); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == ' ') { sb.deleteCharAt(sb.length() - 1); } resultList.add(sb.toString()); } return resultList; } }
|
References
1324. Print Words Vertically