- Roman to Integer
Example
Solution 1
Time complexity: O(n), space complexity: O(1)
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> symbol = new HashMap<>();
symbol.put('I', 1);
symbol.put('V', 5);
symbol.put('X', 10);
symbol.put('L', 50);
symbol.put('C', 100);
symbol.put('D', 500);
symbol.put('M', 1000);
int num = 0;
int pre = -1;
for(char c: s.toCharArray()) {
int temp = symbol.get(c);
if(pre > -1 && pre < temp) {
num -= 2*pre;
}
num += temp;
pre = temp;
}
return num;
}
Solution 2
Time complexity: O(), space complexity: O(1)
class Solution {
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);
if(s.length() == 1)
return map.get(s.charAt(0));
int i = s.length()-1;
int result = map.get(s.charAt(i));
for(int j=i-1; j>=0; j--){
int a = map.get(s.charAt(i));
int b = map.get(s.charAt(j));
if(a > b){
result -= b;
}else if(a <= b){
result += b;
}
i--;
}
return result;
}
}