列表

详情


1324. 竖直打印单词

给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。
每个单词只能放在一列上,每一列中也只能有一个单词。

 

示例 1:

输入:s = "HOW ARE YOU"
输出:["HAY","ORO","WEU"]
解释:每个单词都应该竖直打印。 
 "HAY"
 "ORO"
 "WEU"

示例 2:

输入:s = "TO BE OR NOT TO BE"
输出:["TBONTB","OEROOE","   T"]
解释:题目允许使用空格补位,但不允许输出末尾出现空格。
"TBONTB"
"OEROOE"
"   T"

示例 3:

输入:s = "CONTEST IS COMING"
输出:["CIC","OSO","N M","T I","E N","S G","T"]

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: vector<string> printVertically(string s) { } };

golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2022-12-04 12:25:55

func printVertically(s string) []string {
	strs := strings.Split(s, " ")
	chars := make([]byte, len(strs))
	blank := strings.Repeat(" ", len(strs))

	ret := make([]string, 0)
	for true {
		for i, str := range strs {
			//取各个字符串的len(ret)位
			if len(ret) < len(str) {
				chars[i] = str[len(ret)]
			} else {
				chars[i] = ' '
			}
		}
		//如果全空,则结束
		if string(chars) == blank {
			return ret
		}
		ret = append(ret, strings.TrimRight(string(chars), " "))
	}
	return ret
}

javascript 解法, 执行用时: 68 ms, 内存消耗: 41.1 MB, 提交时间: 2022-12-04 12:25:00

/**
 * @param {string} s
 * @return {string[]}
 */
const printVertically = s => {
  const ret = [];
  for (let i = 0, idx = 0, word = 0; i < s.length; ++i, ++idx) {
    const char = s[i];
    if (char === ' ') { ++word; idx = -1; continue; }
    if (ret[idx] === undefined) { ret[idx] = ' '.repeat(word) + char; continue; }
    ret[idx].length !== word && (ret[idx] += ' '.repeat(word - ret[idx].length));
    ret[idx] += char;
  }
  return ret;
};

cpp 解法, 执行用时: 0 ms, 内存消耗: 6.2 MB, 提交时间: 2022-12-04 12:24:22

class Solution {
public:
    vector<string> printVertically(string s) {
        stringstream in(s);
        vector<string> words;
        string _word;
        int maxlen = 0;
        while (in >> _word) {
            words.push_back(_word);
            maxlen = max(maxlen, (int)_word.size());
        }
        vector<string> ans;
        for (int i = 0; i < maxlen; ++i) {
            string concat;
            for (string& word: words) {
                concat += (i < word.size() ? word[i] : ' ');
            }
            while (concat.back() == ' ') {
                concat.pop_back();
            }
            ans.push_back(move(concat));
        }
        return ans;
    }
};

python3 解法, 执行用时: 36 ms, 内存消耗: 15 MB, 提交时间: 2022-12-04 12:24:01

class Solution:
    def printVertically(self, s: str) -> List[str]:
        words = s.split()
        maxlen = max(len(word) for word in words)
        ans = list()
        for i in range(maxlen):
            concat = "".join([word[i] if i < len(word) else " " for word in words])
            ans.append(concat.rstrip())
        return ans

python3 解法, 执行用时: 36 ms, 内存消耗: 15 MB, 提交时间: 2022-12-04 12:23:35

class Solution:
    def printVertically(self, s: str) -> List[str]:
        return ["".join(x).rstrip() for x in itertools.zip_longest(*s.split(), fillvalue=" ")]

python3 解法, 执行用时: 32 ms, 内存消耗: 15 MB, 提交时间: 2022-12-04 12:23:07

class Solution:
    def printVertically(self, s: str) -> List[str]:
        arr = s.split(' ')
        # 二维数组, 行数为最长的单词长度,列数为单词个数
        m = len(arr)
        n = max([len(word) for word in arr])
        
        ans = []
        for i in range(n):
            ans.append(''.join([arr[j][i] if i < len(arr[j]) else ' ' for j in range(m)]).rstrip())
        return ans

上一题