Achtung:

  1. Character und String are not the same.
  2. Generic: Character; array: char[] arr;
  3. (A || B): A shortcuts B;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int romanToInt(String s) {
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);
char[] arr = s.toCharArray();
int res = 0;
for (int i = 0; i < arr.length; ++i) {
if (i == arr.length - 1 || map.get(arr[i]) >= map.get(arr[i+1])) res += map.get(arr[i]);
else res -= map.get(arr[i]);
}
return res;
}
}