题目链接:https://leetcode.com/problems/roman-to-integer/
Runtimes:57ms
1、问题
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
2、分析
简单的模式匹配过程,数字参考了这篇文章匹配过程如下:
I : I(1), II(2), III(3), IV(4), IX(9);
V : V(5), VI(6), VII(7), VIII(8);
X : X(10), XX(20), XXX(30), XL(40), XC(90);
L : L(50), LX(60), LXX(70), LXXX(80);
C : C(100), CC(200), CCC(300), CD(400), CM(900);
D : D(500), DC(600), DCC(700), DCCC(800);
M : M(1000), MM(2000), MMM(3000);
3、小结
粗心把 s[i + 2] 写成了 s[i = 2],低级错误。
4、实现
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == 'I')
{
if (i + 1 < s.length())
{
if (s[i + 1] == 'I'){
if (i + 2 < s.length() && s[i + 2] == 'I')
{
sum += 3;
i += 2;
}
else{
sum += 2;
i += 1;
}
}
else if (s[i + 1] == 'V'){
sum += 4;
i += 1;
}
else if(s[i + 1] == 'X'){
sum += 9;
i += 1;
}
else{
sum += 1;
}
}
else {
sum += 1;
}
}
else if (s[i] == 'V'){
if (i + 1 < s.length() && s[i + 1] == 'I'){
if (i + 2 < s.length() && s[i + 2] == 'I')
{
if (i + 3 < s.length() && s[i + 3] == 'I')
{
sum += 8;
i += 3;
}
else{
sum += 7;
i += 2;
}
}
else{
sum += 6;
i += 1;
}
}
else{
sum += 5;
}
}
else if (s[i] == 'X'){
if (i + 1 < s.length()){
if (s[i + 1] == 'X'){
if (i + 2 < s.length() && s[i + 2] == 'X')
{
sum += 30;
i += 2;
}
else{
sum += 20;
i += 1;
}
}
else if (s[i + 1] == 'L'){
sum += 40;
i += 1;
}
else if (s[i + 1] == 'C'){
sum += 90;
i += 1;
}
else{
sum += 10;
}
}
else{
sum += 10;
}
}
else if(s[i] == 'L'){
if (i + 1 < s.length() && s[i + 1] == 'X'){
if (i + 2 < s.length() && s[i + 2] == 'X'){
if (i + 3 < s.length() && s[i + 3] == 'X'){
sum += 80;
i += 3;
}
else{
sum += 70;
i += 2;
}
}
else{
sum += 60;
i += 1;
}
}
else{
sum += 50;
}
}
else if (s[i] == 'C'){
if (i + 1 < s.length()){
if (s[i + 1] == 'C')
{
if (i + 2 < s.length() && s[i + 2] == 'C'){
sum += 300;
i += 2;
}
else{
sum += 200;
i += 1;
}
}
else if (s[i + 1] == 'D'){
sum += 400;
i += 1;
}
else if (s[i + 1] == 'M'){
sum += 900;
i += 1;
}
else{
sum += 100;
}
}
else{
sum += 100;
}
}
else if (s[i] == 'D'){
if (i + 1 < s.length() && s[i + 1] == 'C'){
if (i + 2 < s.length() && s[i + 2] == 'C'){
if (i + 3 < s.length() && s[i + 3] == 'C'){
sum += 800;
i += 3;
}
else{
sum += 700;
i += 2;
}
}
else{
sum += 600;
i += 1;
}
}
else{
sum += 500;
}
}
else if (s[i] == 'M'){
if (i + 1 < s.length() && s[i + 1] == 'M'){
if (i + 2 < s.length() && s[i + 2] == 'M'){
sum += 3000;
i += 2;
}
else{
sum += 2000;
i += 1;
}
}
else{
sum += 1000;
}
}
}
return sum;
}
};
5、反思
效果不错。