13. Roman to Integer
Explanation:
To solve this problem, we can iterate through the input Roman numeral string from left to right. We will keep track of the value of the current symbol and compare it with the value of the next symbol. If the value of the current symbol is less than the value of the next symbol, we subtract the current symbol value from the total result. Otherwise, we add the current symbol value to the total result. By doing this, we handle the cases where subtraction is required in Roman numerals.
Time Complexity:
The time complexity of this solution is O(n), where n is the length of the input Roman numeral string.
Space Complexity:
The space complexity is O(1) as we are using a constant amount of extra space.
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 result = 0;
for (int i = 0; i < s.length(); i++) {
int value1 = map.get(s.charAt(i));
if (i < s.length() - 1) {
int value2 = map.get(s.charAt(i + 1));
if (value1 < value2) {
result -= value1;
} else {
result += value1;
}
} else {
result += value1;
}
}
return result;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.