一、自己想的
只有提到的六種情況是-,其他都是+
public int romanToInt1(String s) {int res = 0;int n = s.length();Map<Character, 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);int flag;for( int i =n-1; i>=0; i-- ) {char c = s.charAt(i);flag = 1;if(c == 'I' && i != n-1 ) {if(s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X') {flag = 0;}}else if(c == 'X' && i != n-1) {if(s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C') {flag = 0;}} else if (c == 'C' && i != n-1) {if(s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M') {flag = 0;}}if(flag == 0){res -= map.get(c);}else {res += map.get(c);}}return res;}
二、官方題解
倒序遍歷,觀察到,只要n[i]>n[i-1]就是減(例如IV),其余情況是加.
當然上述情況和六種情況是充要條件,因為比如"IM"這種是非法羅馬數字。
public int romanToInt1(String s) {int res = 0;int n = s.length();Map<Character, 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);for( int i =n-1; i>=0; i-- ) {int num = map.get(s.charAt(i));if(i!=n-1 && num < map.get(s.charAt(i+1)) ) {res -= num;}else{res += num;}}return res;}