1. 程式人生 > >4.2 LeetCode字串類題目選做(1) —— Roman to Integer & Text Justification

4.2 LeetCode字串類題目選做(1) —— Roman to Integer & Text Justification

字串的題目,首先是一些簡單的字串處理的問題,不涉及到什麼演算法。關鍵點是找規律,思考全面所有的情況。

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

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