首页 > 代码库 > Leetcode Roman to Integer

Leetcode Roman to Integer

用了一下template来打表


    template<class T>
    int indexOf(T array[7], T x){
        for(int i = 0; i < 7; i++){
            if(x == array[i])
                return i;
        }
        return -1;
    }
    int romanToInt(string s) {
        string twos [7] = {"CM","CD","XC", "XL", "IX", "IV", "OO"};
        char ones [7] = {'M', 'D', 'C', 'L', 'X', 'V','I'};
        int val2[7] = {900, 400, 90, 40, 9, 4, -1};
        int val1[7] = {1000, 500, 100, 50, 10, 5, 1};
        
        int ans = 0, n = s.size();
        string tmp;
        for(int i = 0; i < n;){
            if(i < n-1 && indexOf(twos, s.substr(i, 2)) != -1){
                ans += val2[indexOf(twos, s.substr(i, 2))];
                i = i+2;
            }
            else{
                ans += val1[ones, indexOf(ones, s[i])];
                i++;
            }
        }
        return ans;
    }


Leetcode Roman to Integer