这道题目有些细节需要注意:
1、HASHMAP最好给object指定类型
2、replace("a","b")如果转换,会将转换后的值生成新的引用。旧引用不会改变
比如下列代码:
string a = "aabbc";
a.replace("c","f");
system.out.println(a);//此刻结果是aabbc,并没有发生改变,
a=a.replace("c","f");//正解~
题目答案:
class Solution {
public int romanToInt(String s) {
HashMap<String,Integer> romaNum = new HashMap<String,Integer>(14);
romaNum.put("A",4);
romaNum.put("B",9);
romaNum.put("E",40);
romaNum.put("F",90);
romaNum.put("G",400);
romaNum.put("H",900);
romaNum.put("I",1);
romaNum.put("V",5);
romaNum.put("X",10);
romaNum.put("L",50);
romaNum.put("C",100);
romaNum.put("D",500);
romaNum.put("M",1000);
String new_s = s.replace("IV","A").replace("IX","B").replace("XL","E").replace("XC","F").replace("CD","G").replace("CM","H");
int sNum= 0;
for(int i=0;i<new_s.length();i++){
int a=romaNum.get(new_s.charAt(i)+"");
sNum = sNum + a;
}
return sNum;
}
}
```
网友评论