Given 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";