Roman to Integer
来源:互联网 发布:荷兰红灯区知乎 编辑:程序博客网 时间:2024/06/05 00:41
Roman to Integer
Total Accepted: 50788 Total Submissions: 147615My SubmissionsGiven a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Hide Similar Problems
class Solution {public: int romanToInt(string s) {map<string, int> Roman;Roman["M"] = 1000; Roman["CM"] = 900; Roman["D"] = 500;Roman["CD"] = 400; Roman["C"] = 100; Roman["XC"] = 90;Roman["L"] = 50; Roman["XL"] = 40; Roman["X"] = 10;Roman["IX"] = 9; Roman["V"] = 5; Roman["IV"] = 4;Roman["I"] = 1; int result = 0,i = 0;while(i < s.length()){string tmp = s.substr(i,2);if( Roman.count( tmp)){result += Roman[tmp];i += 2;}else{result += Roman[ s.substr(i,1) ];i++;}} return result; }};
1、在map中,由key查找value时,首先要判断map中是否包含key。
2、如果不检查,直接返回map[key],可能会出现意想不到的行为。如果map包含key,没有问题,如果map不包含key,使用下标有一个危险的副作用,会在map中插入一个key的元素,value取默认值,返回value。也就是说,map[key]不可能返回null。
3、map提供了两种方式,查看是否包含key,m.count(key),m.find(key)。
4、m.count(key):由于map不包含重复的key,因此m.count(key)取值为0,或者1,表示是否包含。
5、m.find(key):返回迭代器,判断是否存在。
6、对于下面的场景,存在key就使用,否则返回null,有下面两种写法:
1 if(m.count(key)>0)2 {3 return m[key];4 }5 return null;
1 iter = m.find(key);2 if(iter!=m.end())3 {4 return iter->second;5 }6 return null;
这里需要注意:前一种方法很直观,但是效率差很多。因为前面的方法,需要执行两次查找。因此,推荐使用后一种方法。
7、对于STL中的容器,有泛型算法find(begin,end,target)查找目标,map还提供了一个成员方法find(key)
在map中插入元素 三种插入方式: 2.1.1用insert方法插入pair对象: enumMap.insert(pair<int, Cstring>(1, “One”)); 2.1.2 用insert方法插入value_type对象: enumMap.insert(map<int, Cstring>::value_type (1, “One”)); 2.1.3 用数组方式插入值: enumMap[1] = "One"; enumMap[2] = "Two";
0 0
- Integer to Roman & Roman to Integer
- Integer to Roman & Roman to Integer
- 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
- Integer to Roman and Roman to Integer
- LeetCode Integer to Roman & Roman to Integer
- Roman to Integer/Integer to Roman
- leetcode - roman to integer & integer to roman
- "Roman to Integer" and "Integer to Roman"
- Roman to Integer &&Integer to Roman
- Roman to Integer and Integer to Roman
- Roman to Integer/Integer to Roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- 关于Snaphu(待完善)
- html在不同浏览器里面实现背景音乐的播放
- VS2005 无法调试的一个解决方案
- CentOS查看CPU温度
- XML解析之Jdom解析
- Roman to Integer
- POJ 2135 Farm Tour(费用流)
- 下一步行动
- 10个面向对象的开发原则
- 第六周第五天
- javaSE基础编程——String的转换功能
- [刷题]Min Stack
- 郑州最好的狐臭医院
- VS中修改解决方案/项目/类的名字