题目描述:
题目思路:
- 其实这道题和12题的整数转罗马数字比较类似,核心思想就是用hashmap去将对应的字符串和数字用key,value的形式存储起来
- 然后每次用过hashmap的API接口去查找,但是一定要明白为什么是用hashmap,因为hashmap中查找的时间复杂度是0(1),用哈希表查找的!这才是关键
实现:
public int romanToInt(String s) {
HashMap<String,Integer> map = new HashMap();
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("IV",4);
map.put("IX",9);
map.put("XL",40);
map.put("XC",90);
map.put("CD",400);
map.put("CM",900);
int res = 0;
for(int i = 0; i < s.length(); i++){
if(i+1 < s.length() && map.containsKey(s.substring(i,i+2))){
res += (int)map.get(s.substring(i,i+2));
i++;
}else{
res += (int)map.get(s.substring(i,i+1));
}
}
return res;
}
总结不足:
- 一开始本来想着将字符串转化为字符数组去做,但是后面发现两个字符相加会变成一个整数,解决方法是两个字符相加的中间再加一个“”即可。例如:s1 + “” + s2
- 对hashmap的API接口不熟悉!