1324. Print Words Vertically**

1324. Print Words Vertically**

https://leetcode.com/problems/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.

C++ 实现 1

按空格 split 将 s 中的 word 提取出来, 并求出最大的 word 的长度. 注意 s 本身是以 English letters 开头和结尾的, 这意味着 s = " HOW ARE YOU " 这种例子是不会出现的.

class Solution {
public:
    vector<string> printVertically(string s) {
        vector<string> split_words;
        int max_len = 0;
        for (int i = 0; i < s.size(); ++ i) {
            int j = i;
            while (j < s.size() && s[j] != ' ') ++ j;
            split_words.push_back(s.substr(i, j - i));
            max_len = std::max(max_len, j - i);
            i = j;
        }
        vector<string> res;
        for (int i = 0; i < max_len; ++ i) {
            string word;
            for (auto &w : split_words) {
                word += i < w.size() ? w[i] : ' ';
            }
            // remove trailing spaces
            // 也可以使用 int end = word.find_last_not_of(' ');
            // word.substr(0, end + 1);
            int j = word.size();
            while (j - 1 >= 0 && word[j - 1] == ' ') -- j;
            word = word.substr(0, j);
            res.push_back(word);
        }
        return res;
    }
};
发布了227 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104096022