LeetCode 13 罗马数字转整数
LeetCode13 罗马数字转整数
题目描述
上一题的逆运算,字符串==>数字
样例
输入: "III"
输出: 3
输入: "IV"
输出: 4
输入: "IX"
输出: 9
输入: "LVIII"
输出: 58
解释: L = 50, V= 5, III = 3.
输入: "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.
算法分析
- 1、用哈希表存储 字符和数值的对应关系
- 若
[i,i + 1]的字符串能在哈希表中存在,则表示[i,i + 1]的字符串能表示成一个数值,则ans加上该数值
若不存在,则只能翻译i位置的字符成一个数值,ans加上该数值 - 若是
小大需要减小小 IV 15 => ans -1 +5 == ans + 4
时间复杂度
Java代码
class Solution {
public int romanToInt(String s) {
HashMap<String, Integer> map = new HashMap<String, 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 res = 0;
for(int i = 0; i < s.length(); i++){
if(i + 1 < s.length() && map.get(s.substring(i,i+1))< map.get(s.substring(i+1,i+2))){
res -= map.get(s.substring(i,i+1));
}else{
res += map.get(s.substring(i,i+1));
}
}
return res;
}
}

浙公网安备 33010602011771号