模拟专题4 - leetcode12. Integer to Roman/68. Text Justification★

12. Integer to Roman

题目描述

罗马数字由七个不同的符号表示:I,V,X,L,C,D和M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

输入范围是1-3999

例子

2被写成II(2个1相加);12被写成XII(X+II);27被写成XXVII(XX+V+II)。

从大到小,从左向右写。但是,4并不是IIII,而是IV [5-1=4];同理9被写成[IX]。共有6个数字用减法(4/9/40/90/400/900)。

思想

模拟 - 找出数字中的最大的可转换成roman的数字

解法1 (不是最优,改进见解法2)
依次找出数字中包含的最大的可转化为罗马数字的数字。

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        
        ss = ''
        for i in range(len(nums)):
            while num >= nums[i]:
                num -= nums[i]
                ss += romans[i]
        return ss       

解法2
改进解法1(为了避免很多次的减法运算)

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        
        ss = ''
        for i in range(len(nums)):
            if num >= nums[i]:
                ss += num // nums[i] * romans[i]
                num %= nums[i]
        return ss

解法3(最耗时)
刚开始的解法 - 采用二分找到最后一个小于等于num的数
缺点 - 改善的是常数时间复杂度,很冗余。

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        mapping = {1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC',100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M'}
        lis = [1,4,5,9,10,40,50,90,100,400,500,900,1000]
        ss = ''
        while num:
            pos = self.find1stNum(num, lis)
            ss += num // pos * mapping[pos] 
            num %= pos
        return ss
    
    def find1stNum(self, num, lis):
        # 找到最后一个小于等于num的数
        l = 0
        r = len(lis) - 1
        while l <= r:
            mid = (l + r) >> 1
            if lis[mid] <= num:
                if mid < len(lis)-1 and lis[mid+1] <= num:
                    l = mid + 1
                else:
                    return lis[mid]
            else:
                r = mid - 1

68. Text Justification

题目描述

输入 - 单词数组和宽度maxWidth
要求 -

  1. 格式化文本,是每行有maxWidth宽度个字符,并完全左右对齐;
  2. 贪心地分配你的单词,使每行包含尽可能多的单词;必要时填充额外的空格,使宽度达到maxWidth;
  3. 单词间的空格尽可能均匀分布;如果没法满足均匀分布,左边比右边包含更多的空格;
  4. 最后一行左对齐,且相邻单词间没有额外的空格。

例子

Example 1:

Input:
words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
maxWidth = 16
Output:
[
“This is an”,
“example of text”,
"justification. "
]

Example 2:

Input:
words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”]
maxWidth = 16
Output:
[
“What must be”,
"acknowledgment ",
"shall be "
]

Explanation: Note that the last line is "shall be " instead of “shall be”,
because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified becase it contains only one word.

Example 3:

Input:
words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
maxWidth = 20
Output:
[
“Science is what we”,
“understand well”,
“enough to explain to”,
“a computer. Art is”,
“everything else we”,
"do "
]

思想
法1 - 首先存储每行包含的单词(单词间有空格间隔,每行包含尽可能多的单词),然后调用函数调整行(空格尽可能均匀分布),最后拼接。

法2 - 改善

  1. 在循环的每一步,我们都要执行row.append(word)和width -= len(word);
  2. 当row满了,即width - len(row)[单词间至少用一个空格] - len(word) < 0时,不能添加word;
  3. 调整行(空格尽可能均匀分布)时,采用row[i%(len(row)-1 or 1)] += ’ ’
  4. 对最后一行左对齐,用

解法1(不是最简)

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        wordLen = list(map(lambda x:len(x), words))
        res = []
        row = []
        i = 0
        width = maxWidth
        while i < len(words):
            if width > wordLen[i]:
                width -= (wordLen[i] + 1)
                row.append(words[i] + ' ')    # 单词间空格间隔
            elif width == wordLen[i]:
                width -= wordLen[i]
                row.append(words[i])
            else:
                if row[-1][-1] == ' ':    # 去掉最后一个单词后的空格
                    row[-1] = row[-1][:-1]
                res.append(self.justifyRow(row, maxWidth))
                row = []
                width = maxWidth
                i -= 1
            i += 1
        if row:
            row = ''.join(row)
            res.append(row + ' ' * (maxWidth - len(row)))
        return res
    
    def justifyRow(self, row, maxWidth):
        if len(row) == 1:
            return ''.join(row) + ' ' * (maxWidth - len(row[0]))
        # 均匀填充空格
        space = maxWidth-len(''.join(row))
        m = space // (len(row)-1)  # 两两单词间多填充m个空格
        n = space % (len(row)-1)  # 在前n个空格上, 各添加1个空格

        for i in range(n):
            row[i] += ' '
        return ''.join([word + m * ' ' for word in row[:-1]]) + row[-1]

解法2
简化代码,采用row[i%(len(row)-1 or 1)]和 [’ '.join(row).ljust(maxWidth)]的技巧

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        res = []
        row = []
        width = maxWidth
        for word in words:
            if width - len(row) - len(word) < 0:    # 不能添加word
                for i in range(width):
                    row[i%(len(row)-1 or 1)] += ' '
                res.append(''.join(row))
                width = maxWidth
                row = []
            row.append(word)
            width -= len(word)
        return res + [' '.join(row).ljust(maxWidth)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值