iT邦幫忙

2021 iThome 鐵人賽

DAY 13
1
自我挑戰組

試煉之地 Leetcode 的挑戰系列 第 13

Leetcode 挑戰 Day 13 [13. Roman to Integer]

13. Roman to Integer


今天我們一起挑戰leetcode第13題Roman to Integer!

題目


Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.

Example 1:
Input: s = "III"
Output: 3

Example 2:
Input: s = "IV"
Output: 4

Example 3:
Input: s = "IX"
Output: 9

Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

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

這題是希望我們把羅馬數字轉換成阿拉伯數字,並告訴我們轉換的規則,而規則中大部分是羅馬數字與數字一一對應的,且阿拉伯數字原則上也需由大到小排,但其中有一些特列,譬如4就可以用IV來表示,9可以用IX來表示,90可以用XC來表示,依此類推。
題目會給我們一串字串,並要求回傳一個整數。

HahsMap


按照題目的要求與特性我們可以發現,用一個HashMap可以快速達到把字符轉換成數字,程式碼易讀性也會增加,因此我們可以事先建立HashMap來轉換羅馬數字與數字,接著走訪字串,把走訪到的字元利用HashMap轉換成整數加進我們最後要回傳的變數中

但在過程我們必須做檢查,就是檢查上面提到的特例,我們可以檢查走訪到的數字是否比下個數字大,如果是的話表示此時走訪到例外,我們就不要加進變數中,反而要用減的,這樣才會符合題目要求。

以下是python的程式碼

class Solution:
    def romanToInt(self, s: str) -> int:
        roman_dic = {
            'M': 1000, 
            'D': 500, 
            'C': 100, 
            'L': 50, 
            'X': 10, 
            'V': 5, 
            'I': 1
        }  # 建立雜湊表
        result = 0
        for i in range(len(s)-1):
            if roman_dic[s[i]] < roman_dic[s[i+1]]:  # 發現特例
                result -= roman_dic[s[i]]
            else:
                result += roman_dic[s[i]]
        result += roman_dic[s[-1]]  # 要記得走訪完最後一個
        return result

以下是C++的程式碼

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> umap={
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        int count = 0;
        int length = s.length();
        for(int i=0;i<length-1;i++){
            if(umap[s[i]] < umap[s[i+1]]){
                count -= umap[s[i]];
            }
            else{
                count += umap[s[i]];
            }
        }
        count += umap[s[length-1]];
    return count;
    }
};

上一篇
Leetcode 挑戰 Day 12 [ 26. Remove Duplicates from Sorted Array]
下一篇
Leetcode 挑戰 Day 14 [169. Majority Element]
系列文
試煉之地 Leetcode 的挑戰19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言