---
# System prepended metadata

title: '**Leetcode筆記(Roman to Integer)**'
tags: [easy, math, microsoft, leetcode]

---

# **Leetcode筆記(Roman to Integer)**


:::info
:information_source: 題目 : Roman to Integer, 類型 : math , 等級 : easy
日期 : 2023/06/14，2023/10/18，2023/11/20，2023/12/10
:::


### 嘗試
2023/10/18
```python
class Solution:
    def romanToInt(self, s: str) -> int:
        record = {"I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000}
        res = record[s[0]]

        for i in range(1, len(s)):
            cur = record[s[i]]
            pre = record[s[i - 1]]
            if pre < cur:
                res -= 2 * pre # because in the previous time
                # we had add pre once already
            res += cur
        
        return res
```
2023/11/20
```python
class Solution:
    def romanToInt(self, s: str) -> int:
        hashmap = {"I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000, "None" : 0}
        pre = "None"
        res = 0

        for c in s:
            cur = c
            if hashmap[pre] < hashmap[cur]:
                res -= 2 * hashmap[pre] 
            res += hashmap[c]
            pre = c
        
        return res
```
2023/12/10
```python
class Solution(object):
    def romanToInt(self, s):
        hashmap = {"I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000}
        res = 0

        for i, c in enumerate(s):
            if i >= 1 and hashmap[s[i - 1]] < hashmap[c]:
                res += (hashmap[c] - hashmap[s[i - 1]] * 2)
                continue
            res += hashmap[c]
        
        return res
```

---
### **優化**
用倒敘想，如果pre小於cur，代表不符合規則，代表這個數(比較小的那個pre)要被減掉
如果pre大於cur，代表符合規則，那就加上
初始化要先把最後一位加進來

提供的程式碼的時間和空間複雜度如下：

時間複雜度：O(n)

空間複雜度：O(1)
- 字典的空間使用是固定的
- 程式碼還使用一些變量來存儲中間結果
- 因此，空間複雜度是常量的，不取決於輸入的大小。

```python
class Solution:
    def romanToInt(self, s: str) -> int:
        record = {"I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000}
        res = record[s[-1]] # 初始化最後一個

        for i in range(len(s) - 1, 0, -1):
            cur = record[s[i]]
            pre = record[s[i - 1]]
            res += -pre if cur > pre else pre
        
        return res
```
---


**:warning: 錯誤語法** 
:::warning

:::


**:thumbsup:學習** 
:::success

:::

**思路**


**講解連結**
https://blog.csdn.net/coder_orz/article/details/51448537
Provided by. coder_orz


###### tags: `math` `easy` `leetcode`