class Solution {
public int romanToInt(String s) {
int values[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
String reps[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int index = 0,res=0;
while (s.length()!=0){
if(s.substring(0,1).equals(reps[index])){
res+=values[index];
s = s.substring(1);
}
else if(s.length()>1&&s.substring(0,2).equals(reps[index])){
res+=values[index];
s = s.substring(2);
}
else index++;
}
return res;
}
}
我的思路就是,从左往右进行转换.从左往右是由大到小的.然后检验是否符合一个字符的情况,符合就加上去.如果不符合则检查是否符合两个字符的情况.如果都不符合,就移动到下一个字符.使用的内存和速度相比其他解来说都有点点慢.
另外一个思路就是只检查一个字符.从左往右,如果前一个字符比后一个字符小,则这个字符是负数,变成减.
class Solution {
public int romanToInt(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (i == s.length() - 1) res += zhuanhuan(s.charAt(i));
else
res += zhuanhuan(s.charAt(i)) * (zhuanhuan(s.charAt(i)) < zhuanhuan(s.charAt(i + 1)) ? -1 : 1);
}
return res;
}
public static int zhuanhuan(char c){
switch (c){
case 'M':return 1000;
case 'D':return 500;
case 'C':return 100;
case 'L':return 50;
case 'X':return 10;
case 'V':return 5;
case 'I':return 1;
}
return 0;
}
}
再优化一下速度
class Solution {
public int romanToInt(String s) {
int res = 0,temp=0,temp1=0;
for (int i = 0; i < s.length(); i++) {
temp1 = zhuanhuan(s.charAt(i));
res += temp1 > temp ? temp1-2*temp : temp1;
temp = temp1;
}
return res;
}
public static int zhuanhuan(char c){
switch (c){
case 'M':return 1000;
case 'D':return 500;
case 'C':return 100;
case 'L':return 50;
case 'X':return 10;
case 'V':return 5;
case 'I':return 1;
}
return 0;
}
}