[Java][Leetcode simple] 13. 罗马数字转整数

发布于:2025-05-18 ⋅ 阅读:(22) ⋅ 点赞:(0)

一、自己想的

只有提到的六种情况是-,其他都是+

 public int romanToInt1(String s) {
        int res = 0;
        int n = s.length();
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int flag;
        for( int i =n-1; i>=0; i-- ) {
            char c = s.charAt(i);
            flag = 1;
            if(c == 'I' && i != n-1  ) {
                 if(s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X') {
                      flag = 0;
                 }
            }else if(c == 'X' && i != n-1) {
                if(s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C') {
                    flag = 0;
                }
            } else if (c == 'C' && i != n-1) {
                if(s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M') {
                    flag = 0;
                }
            }

            if(flag == 0){
                res -= map.get(c);
            }else {
                res += map.get(c);
            }
        }

        return res;
    }

二、官方题解

倒序遍历,观察到,只要n[i]>n[i-1]就是减(例如IV),其余情况是加.
当然上述情况和六种情况是充要条件,因为比如"IM"这种是非法罗马数字。
在这里插入图片描述

 public int romanToInt1(String s) {
        int res = 0;
        int n = s.length();
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        for( int i =n-1; i>=0; i-- ) {
            int num = map.get(s.charAt(i));
            if(i!=n-1 &&  num < map.get(s.charAt(i+1)) ) {
                res -= num;
            }else{
                res += num;
            }

        }

        return res;
    }

网站公告

今日签到

点亮在社区的每一天
去签到