LeetCode-Roman to Integer-罗马数字转十进制

https://oj.leetcode.com/problems/roman-to-integer/

将罗马数字字符串转换为十进制数字。

首先将罗马数字每一位对应的数字列出来。然后每次搜索当前后面一部分是否等于其中一个罗马数字。找到匹配的最长的那个罗马数字将其匹配掉即可。

class Solution {
public:
    int romanToInt(string s) {
        string rt[][9]={
            {"I","II","III","IV","V","VI","VII","VIII","IX"},
            {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
            {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
            {"M","MM","MMM","CD","D","DC","DCC","DCCC","CM"},
        }; 
        int res=0;
        int r=s.length();
        int bi=1;
        int count=0;
        while(r){
            int pos=r;
            int len=0;
            int di=0;
            for (int i=8;i>=0;i--){
                string cd=rt[count][i];
                int cl=cd.length();
                if (r-cl<0) continue;
                if (s.substr(r-cl,cl)==cd) {
                    if (cl>len) {
                        len=cl;
                        pos=r-cl;
                        di=i+1;
                    }
                }
            }
            res+=di*bi;
            r=pos;
            count++;
            bi*=10;
        }
        return res;
    }
};

 

posted @ 2014-10-16 15:24  zombies  阅读(154)  评论(0编辑  收藏  举报