Leetcode: Roman To Integer
来源:互联网 发布:南京淘宝兼职模特招聘 编辑:程序博客网 时间:2024/06/01 08:02
这道题本来很简单,可是需要注意的是从细节上进行性能改进。一开始我是用Map来存储罗马字母和数字的对应关系,结果发现性能比较差。而改为switch,并且将之写成子函数,并将函数设置Inline,性能得到改进。
因此,如果需要建立映射关系的时候,如果映射的组数比较少的时候,应该尝试使用switch来建立映射关系。如果子函数较小,且被频繁调用,那么应该将该函数设置为inline。这样函数代码会内嵌到代码中,免除了函数调用的开销。
代码:
class Solution { inline int romanCharToInt(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; } }public: int romanToInt(string s) { /* map<char,int> m; m['I'] = 1; m['V'] = 5; m['X'] = 10; m['L'] = 50; m['C'] = 100; m['D'] = 500; m['M'] = 1000; */ int sum = 0; for(int i = ((int)s.length() - 1); i >= 0; i--) { if(i + 1 == (int)s.length()) sum += romanCharToInt(s[i]); else { int t = romanCharToInt(s[i]); if(t < romanCharToInt(s[i + 1])) { sum -= t; } else sum += t; } } return sum; }};
0 0
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- C/C++预处理命令
- C宏参字符串化操作
- 黑马程序员--对面向对象的理解(二)--继承
- 【Github教程】史上最全github使用方法:github入门到精通
- 利用浏览器CSS渲染原理写出高性能的CSS代码
- Leetcode: Roman To Integer
- ASP.NET中用后台代码创建DataTable和HTML表格
- Node.js async in practice: When to use what?
- 多线程的举例
- 最常见的unity基于渲染级别的优化技术:(occlusionclling)、(LODGroup)、(LightMapping)
- 【codeforces #282(div 1)】AB题解
- 黑马程序员--对面向对象的理解(一)--封装
- 【leetcode】 Add Two Numbers
- Android学习笔记の一