本文主要記錄一下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數字查找映射進行累加。
doc