class Solution {
public int romanToInt(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
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('0',0);
int flag=0;
int res=0;
int len=s.length();
for(int i=1;i<len;i++){
if(flag==1){
flag=0;
continue;
}
if(map.get(s.charAt(i))<=map.get(s.charAt(i-1))){
res=res+map.get(s.charAt(i-1));
flag=0;
}
else{
res=res+map.get(s.charAt(i))-map.get(s.charAt(i-1));
flag=1;
}
}
if(flag==0){
res=res+map.get(s.charAt(len-1));
}
return res;
}
}
Leetcode 13. Roman to Integer
最新推荐文章于 2022-03-19 13:18:35 发布