import java.util.ArrayList;
import java.util.List;
/**
* @Class PrintVertically
* @Description 1324. 竖直打印单词
* 给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
* 单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。
* 每个单词只能放在一列上,每一列中也只能有一个单词。
* <p>
* 示例 1:
* 输入:s = "HOW ARE YOU"
* 输出:["HAY","ORO","WEU"]
* 解释:每个单词都应该竖直打印。
* "HAY"
* "ORO"
* "WEU"
* <p>
* 示例 2:
* 输入:s = "TO BE OR NOT TO BE"
* 输出:["TBONTB","OEROOE"," T"]
* 解释:题目允许使用空格补位,但不允许输出末尾出现空格。
* "TBONTB"
* "OEROOE"
* " T"
* <p>
* 示例 3:
* 输入:s = "CONTEST IS COMING"
* 输出:["CIC","OSO","N M","T I","E N","S G","T"]
* <p>
* <p>
* 提示:
* 1 <= s.length <= 200
* s 仅含大写英文字母。
* 题目数据保证两个单词之间只有一个空格。
* @Author
* @Date 2020/6/23
**/
public class PrintVertically {
}
public static List<String> printVertically(String s) {
if (s == null) {
return null;
}
String[] strings = s.split(" ");
int maxlen = 0;
for (int i = 0; i < strings.length; i++) {
maxlen = Math.max(maxlen, strings[i].length());
}
List<String> stringList = new ArrayList<>();
for (int j = 0; j < maxlen; j++) {
// 保存竖直排列后的一行
StringBuilder temp = new StringBuilder("");
// blankTemp保存每行大写字符之间的空格,最后一个大写字符后的空格串直接丢弃
StringBuilder blankTemp = new StringBuilder("");
for (int i = 0; i < strings.length; i++) {
if (j >= strings[i].length()) {
blankTemp.append(" ");
} else {
temp.append(blankTemp);
blankTemp = new StringBuilder("");
temp.append(strings[i].charAt(j));
}
}
stringList.add(temp.toString());
}
return stringList;
}
// 测试用例
public static void main(String[] args) {
String s = "HOW ARE YOU";
List<String> ans = printVertically(s);
System.out.print("demo01 result:[");
for (int i = 0; i < ans.size(); i++) {
System.out.print("," + ans.get(i));
}
System.out.println("]");
s = "TO BE OR NOT TO BE";
ans = printVertically(s);
System.out.print("demo02 result:[");
for (int i = 0; i < ans.size(); i++) {
System.out.print("," + ans.get(i));
}
System.out.println("]");
s = "CONTEST IS COMING";
ans = printVertically(s);
System.out.print("demo03 result:[");
for (int i = 0; i < ans.size(); i++) {
System.out.print("," + ans.get(i));
}
System.out.println("]");
}