当前位置:网站首页>【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;
}
}
边栏推荐
猜你喜欢

星盟-pwn-fog

Interpretation of the paper: Cross-Modality Fusion Transformer for Multispectral Object Detection

Building a data ecology for feature engineering - Embrace the open source ecology, OpenMLDB fully opens up the MLOps ecological tool chain
![swagger错误:WARN i.s.m.p.AbstractSerializableParameter - [getExample,421] - Illegal DefaultValue null](/img/46/6ceeb330821d28b44742436da4123c.png)
swagger错误:WARN i.s.m.p.AbstractSerializableParameter - [getExample,421] - Illegal DefaultValue null

将一个excel文件中多个sheet页“拆分“成多个“独立“excel文件

Day 81

构建面向特征工程的数据生态 ——拥抱开源生态,OpenMLDB全面打通MLOps生态工具链

Use the adb command to manage applications

2022DASCTF X SU 三月春季挑战赛 checkin ROPgadget进阶使用

OpenMLDB Pulsar Connector:高效打通实时数据到特征工程
随机推荐
C语言-6月10日-my_strcat函数的编写
Matplotlib找不到字体,打印乱码
Jetpack使用异常问题集锦
OpenMLDB: Consistent production-level feature computing platform online and offline
JS事件循环机制
Fourth Paradigm OpenMLDB optimization innovation paper was accepted by VLDB, the top international database association
Thesis unscramble TransFG: A Transformer Architecture for Fine - grained Recognition
Interpretation of the paper: Cross-Modality Fusion Transformer for Multispectral Object Detection
详解程序执行过程
Node stepping on the pit 80 port is occupied
OpenMLDB Pulsar Connector:高效打通实时数据到特征工程
连接数据库时出现WARN: Establishing SSL connection without server‘s identity verification is not recommended.
厂商推送平台-华为接入
JVM tuning and finishing
Day 69
The official website of OpenMLDB is upgraded, and the mysterious contributor map will take you to advance quickly
经纬度求距离
第六届蓝帽杯 EscapeShellcode
Promise.race learning (judging the fastest execution of multiple promise objects)
Visual studio2019 配置使用pthread