LeetCode 13 Roman to Integer(罗马数到整型数)
来源:互联网 发布:大数据公司排名 编辑:程序博客网 时间:2024/05/29 09:25
翻译
给定一个罗马数字,将其转换到整型数值。输入被保证在1到3999之间。
原文
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
一开始就没有构思好,虽然按上一题的套路可以走下去,但结果就是像我下面这样……代码凌乱……
public class Solution{ public int RomanToInt(string s) { int result = 0; Type R = typeof(Roman); string first, second; if (s.Length > 1) { first = s.Substring(0, 1); second = s.Substring(0, 2); } else { first = s.Substring(0, 1); second = ""; } foreach (var r in Enum.GetNames(R).Reverse()) { while ((r.Length == 1 && first == r) || (r.Length == 2 && second == r)) { result += int.Parse(Enum.Format(R, Enum.Parse(R, r), "d")); int lenR = r.Length, lenS = s.Length; if (lenS - lenR < 1) s = ""; else s = s.Substring(lenR, lenS - lenR); if (s.Length > 1) { first = s.Substring(0, 1); second = s.Substring(0, 2); } else if (s.Length == 1) { first = s.Substring(0, 1); second = ""; } else { first = ""; second = ""; } } } return result; }}public enum Roman{ M = 1000, CM = 900, D = 500, CD = 400, C = 100, XC = 90, L = 50, XL = 40, X = 10, IX = 9, V = 5, IV = 4, I = 1};
虽然吧,可以运行……但是效率也太低了,简直不忍直视……于是还是像其他大神学习学习……
下面这段代码深深的打动了我……数组作为数组的索引……我最不常用的用法了……
class Solution {public: int romanToInt(string s) { unordered_map<char, int> map = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; int ret = 0; for (int idx = 0; idx < s.size(); ++idx) { if ((idx < s.size()-1) && (map[s[idx]] < map[s[idx+1]])) { ret -= map[s[idx]]; } else { ret += map[s[idx]]; } } return ret; }};
这个算法呢,充分利用了罗马数字两个数字前后顺序的关系,也就是说如果是I在V前面,也就是IV,它代表4,反之代表6。再搭配C++的unordered_map,可以巧妙的通过数组来进行判断而达到对ret或加或减的目的。
我需要好好体会了……
2 0
- LeetCode 13 Roman to Integer(罗马数到整型数)
- LeetCode 12 Integer to Roman(整型数到罗马数)
- 4.Roman to integer(integer to roman罗马数和整型数的相互转换)
- leetcode系列(四):罗马数Roman to Integer
- Roman to Integer | Leetcode 罗马数字转换为整型数
- leetcode 12 Integer to Roman(整型数转换为罗马数字)
- LeetCode Integer to Roman(数字转罗马)
- leetcode 12 ,13 Integer to Roman &&Roman to Integer 罗马与阿拉伯数组转换
- LeetCode-13-Roman to Integer(罗马数字转换为整型数字)
- LeetCode Roman to Integer 罗马字符转数字 解题报告
- Leetcode 12 Integer to Roman整数变罗马
- 【LeetCode-面试算法经典-Java实现】【012-Integer to Roman(数字转罗马字符)】
- leetcode——String to Integer (atoi) 字符串转换为整型数(AC)
- LeetCode (13)Roman to Integer
- leetcode-13:Roman to Integer
- leetcode 13 Roman to Integer
- Leetcode【13】:Roman to Integer
- [leetcode 13] Roman to Integer
- soap协议
- 从最大似然到EM算法浅解
- js判断是否存在滚动条
- swift 拨打电话
- Visual studio 2015中Kinect2+OpenCV3.00环境搭建
- LeetCode 13 Roman to Integer(罗马数到整型数)
- 17.2.2.2 Slave Status Logs
- linux shell — 4.文件和目录管理(1)
- android 字符串截取
- 关于编译性语言、解释性语言和脚本语言的区别
- 程序4---分解质因数
- opencv点目标追踪
- 退到无路可退时,再退一步,以发起反击。这就是给自己要留出最后一步的理由。
- textfield的leftview不能重复