题目来自leetcode,算是非常简单的题目。
Roman numerals are represented by seven different symbols:
I
,V
,X
,L
,C
,D
andM
.Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000For example, two is written as
II
in Roman numeral, just two one's added together. Twelve is written as,XII
, which is simplyX
+II
. The number twenty seven is written asXXVII
, which isXX
+V
+II
.Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not
IIII
. Instead, the number four is written asIV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asIX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III" Output: 3Example 2:
Input: "IV" Output: 4Example 3:
Input: "IX" Output: 9Example 4:
Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.Example 5:
Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4。
写一堆条件判断可以解决,但是太罗嗦。可以考虑使用parellel_array去简化问题。用C++的话直接用两个map就搞定了。
第一个map<char, int>w匹配每个元素的abs(权值);
第二个map<char, int>p定义两个元素的距离,匹配每个元素可以搭配的元素, 若p[a] -p[b]==1,那么a元素可以放在b元素后面,且此时a元素的权值w为负数。
代码如下:
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
map<char, int> w;
map<char, int> p;
w['I'] = 1;
w['V'] = 5;
w['X'] = 10;
w['L'] = 50;
w['C'] = 100;
w['D'] = 500;
w['M'] = 1000;
p['I'] = 0;
p['V'] = 1;
p['X'] = 1;
p['L'] = 2;
p['C'] = 2;
p['D'] = 3;
p['M'] = 3;
for(int i = 0; i < s.size(); i ++) {
if(i + 1 < s.size() && p[s[i]] == p[s[i + 1]] - 1) {
sum += w[s[i + 1]] - w[s[i]];
i ++;
}
else {
sum += w[s[i]];
}
}
return sum;
}
};