LeetCode 13. LeetCode13-罗马数字转整数-20200608-java
原题链接
简单
作者:
bmdxyn0725
,
2020-06-08 17:09:41
,
所有人可见
,
阅读 519
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> dict = new HashMap();
dict.put('I',1);
dict.put('V',5);
dict.put('X',10);
dict.put('L',50);
dict.put('C',100);
dict.put('D',500);
dict.put('M',1000);
int res = 0;
int cur = s.length() -1;
// pre指针总是向左走, cur与pre之间持[0,1]的距离.
for(int pre = s.length() - 1; pre >= 0; pre--){
if(dict.get(s.charAt(pre)) < dict.get(s.charAt(cur))){
res -= dict.get(s.charAt(pre));
cur = pre - 1;
}else{
res += dict.get(s.charAt(pre));
cur = pre;
}
}
return res;
}
}