50:Roman to Integer

来源:互联网 发布:360浏览器网络连接错误 编辑:程序博客网 时间:2024/05/22 00:27

题目:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

下面解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目题目

解析:从前往后扫描字符串,逐个字符的扫描。但我们需要注意 4,9, 40,90,400,500 这 6 个数的表示,因为需要用两个罗马字符来表示这 6 个数。当我们在扫描字符串时,如果发现当前比下一个大,比如 IV = 5 - 1,这时候我们需要将这两个字符一起考虑

代码如下:

// 时间复杂度 O(n),空间复杂度 O(1)class Solution {public:        inline int map(const char c) {                switch (c) {                        case 'I' : return 1;                        case 'V' : return 5;                        case 'X' : return 10;                        case 'L' : return 50;                        case 'C' : return 100;                        case 'D' : return 500;                        case 'M' : return 1000;                        default : return 0;                }        }        int romanToInt(const string& s) {                int integer = 0;                for (int i = 0; i < s.size(); ) {                        if (i != s.size()  - 1 && map[s[i]] < map[s[i + 1]]) {                                integer += map[s[i + 1]] - map[s[i]];                                ++2;                        }                        else {                                integer += map[s[i]]                                ++i;                        }                }                return integer;        }};
0 0
原创粉丝点击