本文主要记录一下leetcode之罗马数字转整数
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/roman-to-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
static Map<Character,Integer> map = new HashMap<>();
static {
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
map.put('A',4);
map.put('B',9);
map.put('Q',40);
map.put('P',90);
map.put('E',400);
map.put('F',900);
}
public int romanToInt(String s) {
s = s.replace("IV","A").
replace("IX","B").
replace("XL","Q").
replace("XC","P").
replace("CD","E").
replace("CM","F");
Integer result=0;
for(char num : s.toCharArray()){
result += map.get(num);
}
return result;
}
}
这里采用HashMap对罗马数字与阿拉伯数字进行映射,另外对于特殊的组合罗马数字进行替换,最后遍历char数字查找映射进行累加。