题目描述
题目链接:13. Roman to Integer
Roman numerals are represented by seven different symbols:
I
,V
,X
,L
,C
,D
andM
.Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, two is written as
II
in Roman numeral, just two one’s added together. Twelve is written as,XII
, which is simplyX
+II
. The number twenty seven is written asXXVII
, which isXX + V + II
.Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not
IIII
. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:I can be placed before
V
(5) andX
(10) to make 4 and 9. X can be placed beforeL
(50) andC
(100) to make 40 and 90. C can be placed beforeD
(500) andM
(1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
例子
例子 1
Input: “III” Output: 3
例子 2
Input: “IV” Output: 4
例子 3
Input: “IX” Output: 9
例子 4
Input: “LVIII” Output: 58 Explanation: L = 50, V= 5, III = 3.
例子 5
Input: “MCMXCIV” Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
解题思路
这道题木关键是最后一部分,理清楚哪些字符可以放在哪些字符前做减法即可,其余部分可以按从小到大的顺序从后往前依次相加对应字符,代码如下:
#include <string>
class Solution {
public:
int romanToInt(std::string s) {
int result = 0;
int ptr = s.length() - 1;
// 0 ~ 3
findChar(s, 1, ptr, 'I', result);
// 4 ~ 8
findChar(s, 5, ptr, 'V', result);
findChar(s, -1, ptr, 'I', result);
// 9 ~ 39
findChar(s, 10, ptr, 'X', result);
findChar(s, -1, ptr, 'I', result);
findChar(s, 10, ptr, 'X', result);
// 40 ~ 80
findChar(s, 50, ptr, 'L', result);
findChar(s, -10, ptr, 'X', result);
// 90 ~ 390
findChar(s, 100, ptr, 'C', result);
findChar(s, -10, ptr, 'X', result);
findChar(s, 100, ptr, 'C', result);
// 400 ~ 800
findChar(s, 500, ptr, 'D', result);
findChar(s, -100, ptr, 'C', result);
// 900 ~ 3900
findChar(s, 1000, ptr, 'M', result);
findChar(s, -100, ptr, 'C', result);
findChar(s, 1000, ptr, 'M', result);
return result;
}
private:
void findChar(std::string s, int change, int& ptr, char c, int& result) {
while (ptr >= 0 && s[ptr] == c) {
result += change;
ptr--;
}
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1)
GitHub 代码同步地址: 13.RomanToInteger.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions