1 题目:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

2 思路

和上一道反过来,好吧,但是思路不一样。

我写的代码思路一样,要考虑一些特殊情况,比较复杂。

别人代码的思路倒是不错: 下面的那个思路,倒序遍历,如果大于5或50或500,那么就是减了,否则就是加。罗马数字小数字在左边是减,且仅限一位。

https://leetcode.com/discuss/2369/solution-for-this-question-but-dont-know-there-any-easier-way

这个是用 哈希函数实现的,我也想过用哈希函数,但是不是这样的,我想的是那个数组全部哈希一遍- -。

https://leetcode.com/discuss/23778/my-accepted-java-code-280-310ms

 

3 代码:

我的

 public int romanToInt(String s) {
        String[] M = {"","M","MM","MMM"};
        String[] C = {"","C","CC","CCC","D","CD","DC","DCC","DCCC","CM"};
        String[] X = {"","X","XX","XXX","L","XL","LX","LXX","LXXX","XC"};
        String[] V = {"","I","II","III","V","IV","VI","VII","VIII","IX"};
        int num = 0;
        for(int i = M.length-1; i>=0 ; i--){
            if(s.startsWith(M[i])){
                num = num + i*1000;
                s = s.substring(i);
                break;
            }
        }
        
        for(int j = C.length-1; j>=0; j--){
            if(s.startsWith(C[j])){
                 s = s.substring(C[j].length());
          //5和4要反过来,先检测CD再检测D,反之,就检测不到D了
if(j==5) j = 4; else if( j==4) j=5; num = num + j*100; break; } } for(int k = X.length-1; k>=0;k--){ if(s.startsWith(X[k])){ s = s.substring(X[k].length()); if(k==5) k = 4; else if( k==4) k=5; num = num + k*10; break; } } for(int i = V.length-1; i>=0; i--){ if(s.startsWith(V[i])){ if(i==5) i = 4; else if( i==4) i=5; num = num + i; break; } } return num; }

好的思路:

public static int romanToInt(String s) {
    int res = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        char c = s.charAt(i);
        switch (c) {
        case 'I':
            res += (res >= 5 ? -1 : 1);
            break;
        case 'V':
            res += 5;
            break;
        case 'X':
            res += 10 * (res >= 50 ? -1 : 1);
            break;
        case 'L':
            res += 50;
            break;
        case 'C':
            res += 100 * (res >= 500 ? -1 : 1);
            break;
        case 'D':
            res += 500;
            break;
        case 'M':
            res += 1000;
            break;
        }
    }
    return res;
}

哈希函数:

public class Solution {
    private static final Map<Character, Integer> maps = new HashMap<>();
    static{
        maps.put('I', 1);
        maps.put('V', 5);
        maps.put('X', 10);
        maps.put('L', 50);
        maps.put('C', 100);
        maps.put('D', 500);
        maps.put('M', 1000);
    }

    public int romanToInt(String s) {
        int previousNum = maps.get(s.charAt(0));
        int result = maps.get(s.charAt(0));

        for (int i = 1; i < s.length(); i++){
            if (previousNum < maps.get(s.charAt(i))){
                    result = result - (2*previousNum);
            } 

            previousNum = maps.get(s.charAt(i));
            result += previousNum;
        }
        return result;
    }
}