当前位置:网站首页>【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;
}
}
边栏推荐
- JVM tuning and finishing
- Regular expression replacement for batch quick modification code
- c语言-数据存储部分
- Day 80
- 127.0.0.1 connection refused
- Fourth Paradigm OpenMLDB optimization innovation paper was accepted by VLDB, the top international database association
- 无效的修订:3.18.1-g262b901-dirty
- C语言-7月19日-指针的学习
- Day 84
- 贡献者任务第三期精彩来袭
猜你喜欢
随机推荐
vim 编辑器使用学习
JS事件循环机制
解决npm warn config global `--global`, `--local` are deprecated. use `--location=global` instead.
The whole process of Tinker access --- Compilation
开发公众号授权遇到的redirect_uri参数错误
Day 82
C语言-7月22日- NULL和nullptr的深入了解以及VScode对nullptr语句报错问题的解决
swagger常用注释API @ApiModel、@ApiModelProperty的用法
Wonderful linkage | OpenMLDB Pulsar Connector principle and practical operation
本地缓存cookie的使用
OpenMLDB v0.5.0 released | Performance, cost, flexibility reach new heights
Node stepping on the pit 80 port is occupied
mysql basic summary
The Summer of Open Source 2022 is coming | Welcome to sign up for the OpenMLDB community project~
Day 84
Day 75
详解程序执行过程
Thesis unscramble TransFG: A Transformer Architecture for Fine - grained Recognition
8-byte standard request parsing during USB enumeration
OpenMLDB + Jupyter Notebook: Quickly Build Machine Learning Applications









