The idea is to loop the String, take each char for count. A map is implemented to save Roman char to numbers. And notice if (index) < (index+1), use (i + 1) - (i) to the result. This affect the loop condition too.
public class Solution {
public int romanToInt(String s) {
if(s == null){
return 0;
}
Map<Character, Integer> romanIntegerTable = new HashMap<Character,Integer>();
romanIntegerTable.put('I', 1);
romanIntegerTable.put('V', 5);
romanIntegerTable.put('X', 10);
romanIntegerTable.put('L', 50);
romanIntegerTable.put('C', 100);
romanIntegerTable.put('D', 500);
romanIntegerTable.put('M', 1000);
int result = 0;
int index = 0;
while(index < s.length() - 1){
if(!romanIntegerTable.containsKey(s.charAt(index)) || !romanIntegerTable.containsKey(s.charAt(index + 1))){
return Integer.MIN_VALUE;
}
if(romanIntegerTable.get(s.charAt(index)) < romanIntegerTable.get(s.charAt(index + 1))){
result += (romanIntegerTable.get(s.charAt(index + 1)) - romanIntegerTable.get(s.charAt(index++)));
index++;
}else{
result += romanIntegerTable.get(s.charAt(index++));
}
//index++;
}
if(index == s.length() - 1){
result += romanIntegerTable.get(s.charAt(index));
}
return result;
}
}
没有评论:
发表评论