算法题笔记-easy难度-03罗马数字转整数(leetcode第13题)

142 阅读1分钟

题目地址:leetcode-cn.com/problems/ro…

思路:字符串匹配的思路,按照题目规则穷举出所有的组合,然后从前往后去匹配字符串。根据匹配到的数量,来对角标进行+1或者+2的操作

上代码:

class Solution {
    public int romanToInt(String s) {
        Map<String,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);
        // 特殊情况
        map.put("IV",4);
        map.put("IX",9);
        map.put("XL",40);
        map.put("XC",90);
        map.put("CD",400);
        map.put("CM",900);

        // 使用字符串匹配
        int index = 0;
        int result = 0;
        while(index < s.length()) {
            String x = "";//最终参与计算的字符串
            char x1 = s.charAt(index);//当前index指向的字符串
            if (index + 1 < s.length()) {
                char x2 = s.charAt(index+1);
                char[] charArr = new char[2];
                charArr[0] = x1;
                charArr[1] = x2;
                String tmp = new String(charArr);
                if(map.containsKey(tmp)) {
                    x = tmp;
                    index = index+2;
                } else {
                    x = String.valueOf(x1);
                    index = index+1;
                }
            } else {
                x = String.valueOf(x1);
                index = index+1;
            }
            result = result + map.get(x);
        }
        return result;
    }
}