leetcode-13-roman to integer

罗马数字转换为阿拉伯数字,同样是0-3999之内。

class Solution(object):
    def romanToInt(self, s):
        """ :type s: str :rtype: int """
        a=0
        d=["MMM","MM","M"]
        for i in range(3):
            if d[i] in s:
                a=(3-i)*1000
                s.lstrip(d[i])
                break
        c=[ ["CM","DCCC","DCC","DC","D","CD","CCC","CC","C"],
            ["XC","LXXX","LXX","LX","L","XL","XXX","XX","X"],
            ["IX","VIII","VII","VI","V","IV","III","II","I"],
            ]
        for i in range(3):
            for j in range(9):
                if c[i][j] in s and s[0]==c[i][j][0]:
                    a+=(9-j)*(10**(2-i))
                    s.lstrip(c[i][j])
                    break
        return a

将千位和其他3个位数分开。从高位开始遍历,如果首字母匹配而且这个字符在s里面就计算对应的10进制数。因为样本小,可以用in加首字母判断。如果样本多的话应该是 先算list中每个字符的长度x,然后比较s中前x个字符和list中这个字符是否相等。然后lstrip删除。AC 192ms。

c++

class Solution {  
public:  
    int romanToInt(string s) {  
        int ret = toNumber(s[0]);  
        for (int i = 1; i < s.length(); i++) {  
            if (toNumber(s[i - 1]) < toNumber(s[i])) {  
                ret += toNumber(s[i]) - 2 * toNumber(s[i - 1]);  
            } else {  
                ret += toNumber(s[i]);  
            }  
        }  
        return ret;  
    }  

    int toNumber(char ch) {  
        switch (ch) {  
            case 'I': return 1;  
            case 'V': return 5;  
            case 'X': return 10;  
            case 'L': return 50;  
            case 'C': return 100;  
            case 'D': return 500;  
            case 'M': return 1000;  
        }  
        return 0;  
    }  
};  

判断上一位数和下一位数的关系,如果前一位大,就加上。如果前一位小,下一位加上的时候减去2倍前一位数。

你可能感兴趣的:(leetcode-13-roman to integer)