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);
int total = 0;
char prevChar = 'p';
int prev = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (i != s.length() - 1) {
prevChar = s.charAt(i + 1);
prev = map.get(prevChar);
}
char sx = s.charAt(i);
int corr = map.get(sx);
if (prev > corr) {
total -= corr;
} else {
total += corr;
}
}
return total;
}
}```
is this good enough solution ? it's O(n) right
https://leetcode.com/problems/roman-to-integer/?envType=list&envId=xix1yu51
#leetcode my solution
1 messages · Page 1 of 1 (latest)
Detected code, here are some useful tools:
Formatted code
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);
int total = 0;
char prevChar = 'p';
int prev = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (i != s.length() - 1) {
prevChar = s.charAt(i + 1);
prev = map.get(prevChar);
}
char sx = s.charAt(i);
int corr = map.get(sx);
if (prev > corr) {
total -= corr;
}
else {
total += corr;
}
}
return total;
}
}
Helper please have a look, thanks.