LeetCode: 011 - Roman to Integer

Roman to Integer

比較喜歡用到字符串處理的題

我的解法

class Solution(object):
    roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

    def turn(self, s):
        roman = self.roman
        if len(s) == 1:
            return roman[s]
        else:
            return roman[s[-1]] - sum (map(lambda i: roman[i], s[:-1]))

    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        # roman = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']
        roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        # 3999 = 'M M M CM XC IX'
        # 3529 = 'M M M V X X IX'
        dList = []
        i = 0
        while i < len(s):
            j = 1
            while j < 4:
                if i+j >= len(s):
                    dList.append(s[i:i+j])
                    i += j
                    break
                if roman[s[i + j -1]] == roman[s[i+j]] or \
                    roman[s[i + j - 1]] > roman[s[i+j]]:
                    dList.append(s[i: i+j])
                    i += j
                    break
                j += 1
            #i += 1
        return sum(map(self.turn, dList))             

完全稱得上是簡單粗暴並且無腦。
因此效率非常差勁

題外話

這個是補1月2日的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章