[LeetCode] 1324. Print Words Vertically 竖直打印单词


Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.

Example 1:

Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
 "HAY"
 "ORO"
 "WEU"

Example 2:

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
"   T"

Example 3:

Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints:

  • 1 <= s.length <= 200
  • s contains only upper case English letters.
  • It's guaranteed that there is only one space between 2 words.

这道题说是给了一个字符串,里面有一些单词,用空格隔开了。现在让把这些单词从上到下排开,每行放一个单词,然后把每一列上的字母取出来形成新的单词并返回,而且强调了不能有末尾零存在。题目中给了好几个例子可以帮助我们理解题意,首先要做的就是将单词拆分出来,Java 提供了强大的字符串处理函数,可以直接用 Split 来拆分,而 C++ 中就比较麻烦一点,要用到字符串流类来做,将拆分出的单词放到 words 数组中,同时求出最长单词的长度 mxLen,因为返回的结果 res 数组的长度就是 mxLen。拆好了单词之后,就可以开始按顺序取字母了,结果 res 中一共 mxLen 个单词,外层用一个 for 循环来一个一个的创建单词,每个字母要从不同的单词中取,所以要遍历 words 数字,若i大于等于当前 word 单词的长度,说明此时对应的位置为空,则将空格字符加入到 res[i] 中,否则将 word[i] 加入到 res[i] 中。当单词 res[i] 创建成功后,需要移除末尾零,这里直接用个 while 循环移除即可,参见代码如下:


class Solution {
public:
    vector<string> printVertically(string s) {
        istringstream iss(s);
        string t = "";
        vector<string> words;
        int mxLen = 0;
        while (iss >> t) {
            mxLen = max(mxLen, (int)t.size());
            words.push_back(t);
        }
        vector<string> res(mxLen);
        for (int i = 0; i < mxLen; ++i) {
            for (string word : words) {
                if (i >= word.size()) res[i].push_back(' ');
                else res[i].push_back(word[i]);
            }
            while (res[i].back() == ' ') res[i].pop_back();
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1324


参考资料:

https://leetcode.com/problems/print-words-vertically/

https://leetcode.com/problems/print-words-vertically/solutions/484776/c-max-size/


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2022-12-10 20:02  Grandyang  阅读(122)  评论(0编辑  收藏  举报
Fork me on GitHub