• 【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.

    解题思路:题目不难。我的方法是把所有的字符串存入一个二维矩阵中,矩阵的行数是s中单词的数量,列数是s中最长的单词的长度;最后再垂直方向遍历矩阵即可。

    代码如下:

    class Solution(object):
        def printVertically(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            words = s.split(' ')
            max_len = 0
            for w in words:
                max_len = max(max_len,len(w))
    
            res = []
    
    
            grid = [[''] * max_len for _ in words]
    
            for i in range(len(words)):
                for j in range(max_len):
                    if j >= len(words[i]):
                        grid[i][j] = ' '
                        continue
                    grid[i][j] = words[i][j]
    
            for j in range(len(grid[i])):
                val = ''
                for i in range(len(grid)):
                    val += grid[i][j]
                val = val.rstrip()
                res.append(val)
            return res
  • 相关阅读:
    证券市场主体
    证券投资基金
    1.监控系统的重要性
    1.五种世界顶级思维-20190303
    【四校联考】【比赛题解】FJ NOIP 四校联考 2017 Round 7
    【学长出题】【比赛题解】17-09-29
    【codeforces】【比赛题解】#854 CF Round #433 (Div.2)
    【codeforces】【比赛题解】#851 CF Round #432 (Div.2)
    【算法学习】三分法
    【codeforces】【比赛题解】#849 CF Round #431 (Div.2)
  • 原文地址:https://www.cnblogs.com/seyjs/p/12217732.html
Copyright © 2020-2023  润新知