Here’s the question link on Leetcode 13. Roman to Integer:
https://leetcode.com/problems/roman-to-integer/description
Contents
Brute Force: Handle All Subtraction Cases
The straightforward approach is to check for all six special combinations separately.
If we find one, subtract its value. Otherwise, simply add the current character’s value.
We can use a map to store the values of Roman symbols.
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> mp = {
{'I', 1}, {'V', 5},
{'X', 10}, {'L', 50},
{'C', 100}, {'D', 500},
{'M', 1000}
};
int ans = 0;
for(int i = 0; i < s.size(); i++) {
if(i + 1 < s.size()) {
string pair = s.substr(i, 2);
if(pair == "IV" || pair == "IX" ||
pair == "XL" || pair == "XC" ||
pair == "CD" || pair == "CM") {
ans += mp[s[i + 1]] - mp[s[i]];
i++;
continue;
}
}
ans += mp[s[i]];
}
return ans;
}
};
Optimal: Compare With the Next Character
Here’s a much simpler observation!
If the current character has a smaller value than the next character, subtract it. Otherwise, add it.
That’s it. We don’t need to check all six combinations separately.
For example:
s = "MCMXCIV"
Let’s go through it:
| Character | Next character | Operation |
|---|---|---|
| M (1000) | C (100) | +1000 |
| C (100) | M (1000) | -100 |
| M (1000) | X (10) | +1000 |
| X (10) | C (100) | -10 |
| C (100) | I (1) | +100 |
| I (1) | V (5) | -1 |
| V (5) | None | +5 |
Total:
\[ 1000-100+1000-10+100-1+5=1994 \]
Notice how we only need to compare the current character with the next one.
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> mp = {
{'I', 1}, {'V', 5},
{'X', 10}, {'L', 50},
{'C', 100}, {'D', 500},
{'M', 1000}
};
int ans = 0;
for(int i = 0; i < s.size(); i++) {
if(i + 1 < s.size() && mp[s[i]] < mp[s[i + 1]]) {
ans -= mp[s[i]];
}
else {
ans += mp[s[i]];
}
}
return ans;
}
};