【LeetCode Easy】013 Roman to Integer

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;
    }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理