13. 罗马数字转整数

我写的原始代码,不够优雅。
class Solution {
public int romanToInt(String s) {
char[] sChar = s.toCharArray();
int res = 0,n = s.length();
HashMap<Character,Integer> cMap = new HashMap<>();
cMap.put('M',1000);cMap.put('D',500);cMap.put('C',100);cMap.put('L',50);
cMap.put('X',10);cMap.put('V',5);cMap.put('I',1);
if(n == 1) return cMap.get(sChar[0]);
for(int i = 0;i < n - 1;++i){
if(cMap.get(sChar[i]) >= cMap.get(sChar[i + 1])) res += cMap.get(sChar[i]);
else{
res += (cMap.get(sChar[i+1]) - cMap.get(sChar[i]));++i;
}
}
if(cMap.get(sChar[n-2]) >= cMap.get(sChar[n-1])) res += cMap.get(sChar[n-1]);
return res;
}
}
这道题就一个关键点:当前位置的元素比下个位置的元素小,就减去当前值,否则加上当前值。
官方题解:
class Solution {
Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {{
put('I', 1);put('V', 5);put('X', 10);put('L', 50);
put('C', 100);put('D', 500);put('M', 1000);
}};
public int romanToInt(String s) {
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = symbolValues.get(s.charAt(i));
if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
}
浙公网安备 33010602011771号