public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
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 i = 0;
int sum = 0;
int temp = 0;
while (i < s.length() - 1) {
if (map.get(s.charAt(i)) > map.get(s.charAt(i+1))) {
sum += map.get(s.charAt(i));
} else if (map.get(s.charAt(i)) < map.get(s.charAt(i+1))) {
temp += map.get(s.charAt(i));
sum -= temp;
temp = 0;
} else {
temp += map.get(s.charAt(i));
}
i++;
}
sum += map.get(s.charAt(i));
sum += temp;
return sum;
}
Did not run b/c:
Knowing this fact, new solution:
public int romanToInt(String s) {
//int I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000;
Map<Character, Integer> map = new HashMap<Character, Integer>();
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 i = 0;
int sum = 0;
while (i < s.length() - 1) {
if (map.get(s.charAt(i)) >= map.get(s.charAt(i+1))) {
sum += map.get(s.charAt(i));
} else {
sum -= map.get(s.charAt(i));
}
i++;
}
sum += map.get(s.charAt(i));
return sum;
}
Runtime: 8 ms, faster than 14.17% of Java online submissions for Roman to Integer.
Memory Usage: 43 MB, less than 5.11% of Java online submissions for Roman to Integer.
Important Points
How can I make it faster?