当前位置:网站首页>【LeetCode-13】罗马数字转整数
【LeetCode-13】罗马数字转整数
2022-08-11 05:30:00 【Ring*】
7.1 罗马数字转整数【13】
7.1.1 题目描述
7.1.2 方法一:模拟
思路
通常情况下,罗马数字中小的数字在大的数字的右边。若输入的字符串满足该情况,那么可以将每个字符视作一个单独的值,累加每个字符对应的数值即可。
例如 XXVII 可视作 X+X+V+I+I=10+10+5+1+1=27。
若存在小的数字在大的数字的左边的情况,根据规则需要减去小的数字。对于这种情况,我们也可以将每个字符视作一个单独的值,若一个数字右侧的数字比它大,则将该数字的符号取反。
例如 XIV 可视作 X−I+V=10−1+5=14。
class Solution {
Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {
{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
public int romanToInt(String s) {
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = symbolValues.get(s.charAt(i));
if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
}
复杂度分析
- 时间复杂度:O(n),其中 nn 是字符串 s* 的长度。
- 空间复杂度:O(1)。
7.1.3 my answer—哈希表
class Solution {
public int romanToInt(String s) {
Map<Character,Integer> map = new HashMap<>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int ans = 0;
for(int i = 0;i<s.length();i++){
Character ch = s.charAt(i);
if(i<s.length()-1 && map.get(ch)<map.get(s.charAt(i+1))){
ans -= map.get(ch);
}else{
ans += map.get(ch);
}
}
return ans;
}
}
边栏推荐
- C-自定义类型(结构体、枚举、联合)
- 开发公众号授权遇到的redirect_uri参数错误
- 本地缓存cookie的使用
- Jetpack use exception problem collection
- Jetpack's dataBinding
- C语言-内存操作函数
- 智能风控中台设计与落地
- OpenMLDB:线上线下一致的生产级特征计算平台
- Event Preview | On April 23, a number of wonderful sharing sessions of OpenMLDB will come, which will live up to the good time of the weekend
- C语言-7月31日-指针的总结以及typedef关键字
猜你喜欢
随机推荐
swagger错误:WARN i.s.m.p.AbstractSerializableParameter - [getExample,421] - Illegal DefaultValue null
Minutes of OpenMLDB Meetup No.2
编译异常解决
Day 73
The Summer of Open Source 2022 is coming | Welcome to sign up for the OpenMLDB community project~
Intelligent risk control China design and fall to the ground
Use the adb command to manage applications
本地缓存cookie的使用
js 学习进阶(事件高级 pink老师教学笔记)
无效的修订:3.18.1-g262b901-dirty
Node 踩坑之80端口被占用
Promise.race learning (judging the fastest execution of multiple promise objects)
Some formulas for system performance and concurrency
精彩联动 | OpenMLDB Pulsar Connector原理和实操
JS进阶网页特效(pink老师笔记)
第一章 Verilog语言和Vivado初步使用
Matplotlib找不到字体,打印乱码
nepctf Nyan Cat 彩虹猫
mk file introduction
mysql basic summary