Leetcode 13 Roman to Integer 字符串处理+STL

题意:将罗马数字1到3999转化成自然数字,这里用了STL库map将罗马字符映射到自然数字。

I,V,X,L,C,D,M -> 1,5,10,50,100,500,1000

m[s[i]]<m[s[i+1]//如IV 就需要减去1
 1 class Solution {
 2 public:    
 3     map<char,int> m;
 4     Solution(){
 5         const int N = 7;
 6         char str[N+1] = "IVXLCDM";
 7         int num[N] ={1,5,10,50,100,500,1000};    
 8         for (int i = 0; i < N; ++i){
 9             m[str[i]] = num[i];
10         }        
11     }
12     ~Solution(){
13         m.clear();
14     }
15     int romanToInt(string s) {
16         int ans = 0;
17         for(int i = 0;i<s.size()-1;++i){
18             if (m[s[i]]<m[s[i+1]]) ans -= m[s[i]];
19             else ans += m[s[i]];
20         }
21         ans += m[s[s.size() - 1]];
22         return ans;
23     }
24 };
原文地址:https://www.cnblogs.com/onlyac/p/5158889.html