与12题一样的规则,将罗马数字转为整数。
思路
字符串str从左到右遍历,不断将一个长度和两个长度的子字符串与罗马字符匹配,匹配成功就将数值相加
import java.util.*;
import static java.lang.Math.min;
public class leetcode {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int num = romanToInt(str);
System.out.println(num);
}
public static int romanToInt(String s) {
//初始化
int[] Roman_num = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
String[] Roman_str = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
int num = 0,index=12;
boolean equal = false;
for(int i = 0; i<s.length(); ) {
equal =false;
if(s.substring(i,i+1).equals(Roman_str[index])) {
num += Roman_num[index];
i++;
equal = true;
}
else if(s.substring(i).length() >= 2 && s.substring(i,i+2).equals(Roman_str[index])) {
num += Roman_num[index];
i += 2;
equal = true;
}
if(equal == false) index--;
}
return num;
}
}
小结
忘记了String相等不能用==,以至于索引报错,一直在想索引怎么会出错。要注意substring的索引不能超出边界,可以求长度来避免这个情况。