标签:情况下 答案 sub 参考 解题思路 diff new else tab
Category | Difficulty | Likes | Dislikes |
---|---|---|---|
algorithms | Easy (61.07%) | 841 | - |
public int romanToInt(String s) {
int res = 0;
for(int i= 0;i<s.length();i++){
switch(s.charAt(i)){
case ‘I‘: {
if(i+1<s.length() && (s.charAt(i+1) == ‘V‘ || s.charAt(i+1) == ‘X‘)){
res-=1;
break;
}
res+=1;
}
break;
case ‘V‘: res+=5;
break;
case ‘X‘:{
if(i+1<s.length() && (s.charAt(i+1) == ‘L‘ || s.charAt(i+1) == ‘C‘)){
res-=10;
break;
}
res+=10;
}
break;
case ‘L‘: res+=50;
break;
case ‘C‘: {
if(i+1<s.length() && (s.charAt(i+1) == ‘D‘ || s.charAt(i+1) == ‘M‘)){
res-=100;
break;
}
res+=100;
}
break;
case ‘D‘: res+=500;
break;
case ‘M‘: res+=1000;
break;
default:
throw new IllegalArgumentException();
}
}
return res;
}
public int romanToInt(String s) {
int res = 0;
for(int i=0;i<s.length();i++){
if(i+1<s.length() && (toInt(s.charAt(i))<toInt(s.charAt(i+1)))){
res-=toInt(s.charAt(i));
continue;
}
res+=toInt(s.charAt(i));
}
return res;
}
int toInt(char c){
switch(c){
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:
throw new IllegalArgumentException();
}
}
public int romanToInt(String s) {
int res = 0;
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);
for(int i=0;i<s.length();i++){
if(i+1<s.length() && (map.containsKey(s.substring(i, i+2)))){
res+=map.get(s.substring(i, i+2));
i++;
}else{
res+=map.get(s.substring(i, i+1));
}
}
return res;
还不如我的呢
无
标签:情况下 答案 sub 参考 解题思路 diff new else tab
原文地址:https://www.cnblogs.com/mdz3201/p/leetcode_13.html