class Solution {
public int romanToInt(String s) {
HashMap<String, Integer> hm = new HashMap<>();
hm.put("M", 1000);
hm.put("CM", 900);
hm.put("D", 500);
hm.put("CD", 400);
hm.put("C", 100);
hm.put("XC", 90);
hm.put("L", 50);
hm.put("XL", 40);
hm.put("X", 10);
hm.put("IX", 9);
hm.put("V", 5);
hm.put("IV", 4);
hm.put("I", 1);
int num = 0;
for(int i = 0; i < s.length(); i++){
if(i < s.length() - 1 && hm.get(s.substring(i,i+1)) < hm.get(s.substring(i + 1,i + 2))){
num += hm.get(s.substring(i,i + 2));
i += 1;
continue;
}
num += hm.get(s.substring(i, i + 1));
}
return num;
}
}
執行用時 : 41 ms, 在Roman to Integer的Java提交中擊敗了56.70% 的用戶
內存消耗 : 44.1 MB, 在Roman to Integer的Java提交中擊敗了66.14% 的用戶