【LeetCode Easy】013 Roman to Integer

34次阅读

共计 741 个字符,预计需要花费 2 分钟才能阅读完成。

Easy 013 Roman to Integer

Description:

将罗马字母的字符串转换为代表的整数
Roman numerals are usually written largest to smallest from left to right. However, 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.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

My Solution:

  1. 这题不难,用一个 HashMap 存罗马数字和具体数字的对应关系,然后遍历前后两两比较,该加加,该减减

    • 时间复杂度 O(n)

Fast Solution:

    public static int romanToInt(String s) {
        int num = 0;
        int n = s.length();
        
        for (int i = 0; i < n-1; i++) {int curr = map(s.charAt(i));  // 这里 map 是自己写的一个方法,里面用一个 switch,相当于 HashMap 存对应
            int next = map(s.charAt(i+1));
            num = curr < next ? num - curr : num + curr;
            // 当时一直想着用一个 temp 来存减的值,所以没法用 for 就用了 while&point 指针,但其实就是很简单的比后面小的话在总值里面减去就可以,不需要 temp
        }    
        num += map(s.charAt(n-1));       
        return num;
    }

正文完
 0