013_RomanToInteger
#####solution1####faster####
def romanToInt(s):
d={
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
i = 1
count = last = d[s[0]]
while i < len(s):
current = d[s[i]]
if current > last:
count -= last * 2
count += current
last = current
i += 1
return count
# ########solution2########
# def romanToInt(s):
# d = {'I': 1,
# 'V': 5,
# 'X': 10,
# 'L': 50,
# 'C': 100,
# 'D': 500,
# 'M': 1000
# }
# res = 0
# if len(s) < 2:
# return d[s[0]]
# res = res + d[s[0]]
# for i in range(1,len(s)):
# res = res + d[s[i]]
# if d[s[i]] > d[s[i - 1]]:
# res = res - 2 * d[s[i-1]]
# return res
#
#
# if __name__=='__main__':
# m="MCMXCIV"
# print(romanToInt(m))
分析:
current记录当前元素值,last记录前一个元素值,count记录current之前所有元素的和,也就是加上了last。
当current大于last时,count需要先减去last再加上current-last,即count-2*last+current
当current小于last时,count直接加上当前current即可,即count+current
013_RomanToInteger的更多相关文章
随机推荐
- docker其他参考资料
https://yeasy.gitbooks.io/docker_practice/image/build.html https://blog.csdn.net/weixin_42596342/art ...
- Mac进行 usr/bin 目录下修改权限问题,operation not permitted
一般情况下我们在使用mac系统过程中下载一些文件.新建一些项目之后,这些文件都会默认是只读状态,这时我们只需要简单的一句权限设置命令就可以解决 你要修改文件上层目录的路径 但是我们在对 usr/bin ...
- linux查询日志常用命令,经常更新
1.grep命令 grep -c "查询内容" filename ------c,是小写,可以知道你要查询的内容在这个文件中是否存在 grep -C 10 "查询内 ...
- Elastic Stack-Elasticsearch使用介绍(一)
一.前言 Elasticsearch对外提供RESTful API,下面的演示我们主要使用Postman,进行一系列的Demo演示,这款工具方便各位前端大大或者对接口调试的神器: 安装过于简单 ...
- webpack4配置详解之常用插件分享
前言 继上一次webpack的基础配置分享之后,本次将分享一些工作中项目常用的配置插件.也会包含一些自己了解过觉得不错的插件,如有分析不到位的,欢迎纠错,嗯,这些东西文档都有,大佬可绕过. Wepac ...
- 遍历CheckBox根据指定条件做筛选js
$('#del').click(function(){ var checkeds=$('input[name=cid]:checked') checkeds.each(function() { var ...
- 6-3 Articles(a, an, some, the)
1 Definite and Indifinite articles Indefinite articles: a, an, some Definite article: the 2 a and t ...
- [转帖]Go中的下划线
Go中的下划线 https://blog.csdn.net/wanglei9876/article/details/50475864 下划线的作用: 在import 时 是仅引入 init 函数 在正 ...
- 数据标记系列——图像分割 & PolygonRNN++(一)
当前大多数图像语义分割算法都是基于深度学习的方式,但是深度学习的效果很大程度上是依赖于大量训练数据的.目前的图像分割方法无非两种,一种是通过标注人员手动标注,如Cityscapes(提供无人驾驶环境下 ...
- JAVA多线程-内存模型、三大特性、线程池
一.线程的三大特性 原子性.可见性.有序性 1)原子性,即一个操作或者多个操作要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行.原子性其实就是保证数据一致.线程安全一部分. 2)可见性,即 ...