LeetCode-13. 罗马数字转整数(Roman to Integer)

哈希表

//哈希表
class Solution {
public:
    int romanToInt(string s) {
        unordered_map<string, int> nums = {{"I", 1}, {"IV",4}, {"V", 5}, {"IX", 9},{"X", 10},{"XL", 40}, {"L", 50}, {"XC", 90}, {"C", 100}, {"CD", 400}, {"D", 500}, {"CM", 900}, {"M", 1000}};
        int res = 0;
        int length = s.length();
        for(int i = 0; i < length; i++){
        	string two = s.substr(i, 2);
        	string one = s.substr(i, 1);
        	if(nums[two]){
        		res += nums[two];
        		i++;
        	}else{
        		res += nums[one];
        	}
        }
        return res;
    }
};

另一种解法

class Solution {
public:
    int romanToInt(string s) {
        int res = 0;
        int length = s.size();
        int pre = getValue(s[0]);
        for (int i = 1; i < length; ++i)
        {
        	int num = getValue(s[i]);
        	if(num > pre){
        		res -= pre;
        	}else{
        		res += pre;
        	}
        	pre = num;
        }
        res += pre;
        return res;
    }
    int getValue(char c){
    	switch(c){
    		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;
    		default: return 0;
    	}
    }
};

题目链接:https://leetcode-cn.com/problems/roman-to-integer/

发布了42 篇原创文章 · 获赞 2 · 访问量 1424

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/102899227
今日推荐