4.2 LeetCode字符串类题目选做(1) —— Roman to Integer & Text Justification

字符串的题目,首先是一些简单的字符串处理的问题,不涉及到什么算法。关键点是找规律,思考全面所有的情况。

13 Roman to Integer

Roman numerals are represented by seven different symbols: IVXLCD and M.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

(关于罗马数字的规律,不再赘述)

题目解析:

将字符串(罗马数字)解析为整数(阿拉伯数字),关键1,理解罗马数字的规律,2,找到解析它的思路。

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

像这样的罗马数字,我们是从左向右看,但是左边的字符的含义要结合右边的字符,比如IV(4),因此采用从右向左解析字符串,代码如下:

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = dict()
        dic["I"] = 1
        dic["V"] = 5
        dic['X'] = 10
        dic['L'] = 50
        dic['C'] = 100
        dic['D'] = 500
        dic['M'] = 1000
        
        ret = 0
        pre = 0
        s = s[::-1]             
        for char in s:
            num = dic[char]
            if num < pre:
                ret -= num
            else:
                ret += num
                pre = num
                
        return ret

68. Text Justification

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • The input array words contains at least one word.

题目解析:

此题就是慢慢处理,思考各种情况。1,按照限制宽度得到每行的单词的列表;2,分情况(该行1个单词,两个单词,以及末尾一行时)计算单词间空格并拼装成一行的字符串line(此处比较复杂,需考虑许多情况);3,输出结果output。代码如下:

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        ret = [[]]
        s = 0
        line = 0
        for word in words:
            l = len(word)
            if s+l > maxWidth:
                line += 1
                s = l+1
                ret.append([word])
            else:
                s += l+1
                ret[line].append(word)
        
        # print(ret)
        output = []
        for i in range(len(ret)):
            text = ret[i]
            num_word = len(text)
            if i == len(ret) - 1:
                line = ' '.join(text)
                leave_blank = maxWidth - len(line)
                line += ' '*leave_blank
            elif num_word == 1:
                line = text[0] + ' '*(maxWidth - len(text[0]))
            elif num_word == 2:
                blank = maxWidth - len(text[0]) - len(text[1])
                line = text[0] + ' '*blank + text[1]
            else:
                total = sum([len(wd) for wd in text])
                ave_blank = (maxWidth - total) // (num_word - 1)                
                more_blank = (maxWidth - total) - (num_word - 1) * ave_blank
                if not more_blank:
                    line = (' '*ave_blank).join(text)
                elif more_blank == 1:
                    line = text[0] + ' '*(ave_blank+1) + (''*ave_blank).join(text[more_blank:])
                else:
                    line = (' '*(ave_blank+1)).join(text[:more_blank]) + ' '*(ave_blank+1)  + (' '*ave_blank).join(text[more_blank:])
            
            output.append(line)
        
        return output

猜你喜欢

转载自blog.csdn.net/xutiantian1412/article/details/82950649