跳至主要内容

13. Roman to Integer

Hint

class Solution {
public:
int romanToInt(string s)
{
// Create a map to store Roman numeral characters and their integer values

// Initialize the result variable to store the final integer value
// Loop through each character in the string
for ()
{
// Check if the current character value is less than the next character value
// If true, subtract the current character's value from the result
// Otherwise, add the current character's value to the result
}
// Return the final integer value
}
};
class Solution {
public:
int romanToInt(string s)
{
unordered_map<char, int> m = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000},
};

int res = 0;
for (int i = 0; i < s.size(); ++i)
{
if (i < s.size() - 1 && m[s[i]] < m[s[i + 1]])
{
res -= m[s[i]];
}
else
{
res += m[s[i]];
}
}
return res;
}
};
  • T: O(N)O(N)
  • S: O(1)O(1)