LeetCode 13
2020.9.21
我的通过代码
class Solution {
public int romanToInt(String s) {
Map<String,Integer> graph = new HashMap<String,Integer>();
graph.put("I",1); graph.put("V",5); graph.put("X",10); graph.put("L",50);
graph.put("C",100); graph.put("D",500); graph.put("M",1000);
int res = 0;
String[] ss = s.split("");
for(int i=0;i<ss.length;i++) {
if(i+1<ss.length&&graph.get(ss[i])<graph.get(ss[i+1])) {
res+=(graph.get(ss[i+1])-graph.get(ss[i]));
i++;
} else {
res+=graph.get(ss[i]);
}
}
return res;
}
}
这个题目并不难,题目中罗马数字与阿拉伯数字的对应关系刚好可以使用哈希表这样的键值对来完成。
可是事与愿违,这样小数据量的操作,哈希表好像并没有太大的优势,用哈希表运行的时空间消耗反而比单纯的使用switch写的函数要大。
private int getValue(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
数据结构方面还需仔细斟酌。