13. Roman to Integer
来源:互联网 发布:软件测试费用标准 编辑:程序博客网 时间:2024/06/05 04:59
方法1:
class Solution {public: int romanToInt(string s) { vector<char> Roman={'I','V','X','L','C','D','M'}; vector<int> dig={1,5,10,50,100,500,1000}; map<string,int> mp; int n=dig.size(); int i,j; int m=s.size(); int ans=0; for(i=1;i<n;i++) { string tmp=""; if(dig[i]==10||dig[i]==100||dig[i]==1000) { tmp+=Roman[i-2]; tmp+=Roman[i]; mp[tmp]=dig[i]-dig[i-2]; } else { tmp+=Roman[i-1]; tmp+=Roman[i]; mp[tmp]=dig[i]-dig[i-1]; } } for(i=0;i<m;) { if(i<m-1&&mp.find(s.substr(i,2))!=mp.end()) { ans+=mp[s.substr(i,2)]; i+=2; } else { for(j=0;j<n;j++) { if(s[i]==Roman[j]) { ans+=dig[j]; break; } } i++; } } return ans; }};
方法2:
可以简化为若当前罗马数字小于下一位罗马数字,则减去当前数字
class Solution {public: int romanToInt(string s) { vector<char> Roman={'I','V','X','L','C','D','M'}; vector<int> dig={1,5,10,50,100,500,1000}; map<char,int> mp; int i; for(i=0;i<dig.size();i++) mp.insert(std::pair<char,int>(Roman[i],dig[i])); int n=s.size(); if(n==0) return 0; int ans=0; for(i=0;i<n-1;i++) { if(mp[s[i]]<mp[s[i+1]]) ans-=mp[s[i]]; else ans+=mp[s[i]]; } ans+=mp[s[i]]; return ans; }};
0 0
- 13. Roman to Integer
- 13.Roman to Integer
- 13. Roman to Integer
- 13.Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- 13. Roman to Integer
- Android 打造自己的滚动选择器ScrollSelector
- Hibernate的出现和Hinbernate的简单模拟实现
- bzoj1078
- hdu 5875 ACM/ICPC Dalian Online 1008 Function
- 重载赋值函数与复制构造函数
- 13. Roman to Integer
- 技术博客地址
- 原生表单提交的方式
- HDU3339-In Action(最短路+01背包)
- 用OpenCV实现Photoshop算法(七): 调整色相饱和度
- 不同等级raid的读写性能,优缺点,所需最小硬盘数以及结构
- 80x86机器指令
- Intel汇编程序设计-整数算术指令(下)
- Hibernate--什么是持久化?