標籤:

[leetcode algorithms]題目13

13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

自己寫的代碼:

初始化類的時候創建字典和列表,用於存儲數字和羅馬字母的對應關係。倒序遍歷字元串,根據字元轉化為數字,不斷地累加,用last_val存儲上一次出現的字元,如果當前字元小於上一字元則要做減法。運行時間316ms

class Solution: def __init__(self): self.dic = {I: 1, X: 10, C: 100, M: 1000, V: 5, L: 50, D: 500} def romanToInt(self, s): res = 0 last_val = -1 for char in s[::-1]: val = self.dic[char] res += [1, -1][int(val < last_val)] * val last_val = val return res

推薦閱讀:

LeetCode 15. 3Sum
[leetcode algorithms]題目17
LeetCode 125. Valid Palindrome
LeetCode 簡略題解 - 601~700

TAG:LeetCode |