Java
设置一个hashmap,字符为键值,数字为值,从左向右读取字符串中的字符,若后一位的取值比前一位的大,说明需要做减法,否则做加法。O(N)的时间复杂度,但是排名在后1/4。。。
public 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);
int result = 0;
for(int i = 0; i < s.length();){
if(i+1 < s.length() && map.get(s.charAt(i)) < map.get(s.charAt(i+1))){
result = result + map.get(s.charAt(i+1)) - map.get(s.charAt(i));
i += 2;
}else{
result = result + map.get(s.charAt(i));
++i;
}
}
return result;
}
}