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的更多相关文章
随机推荐
- Starting sshd: /var/empty/sshd must be owned by root and not group or world-writable.
Starting sshd: /var/empty/sshd must be owned by root and not group or world-writable. [FAILED] ...
- Ambari与Kerberos 集成
Kerberos 介绍 Kerberos 是一个网络认证的框架协议,其设计的初衷便是通过密钥系统为 Client 和 Server 应用程序之间提供强大的认证服务.在使用 Kerberos 认证的集群 ...
- 【转】Android OkHttp3简介和使用详解
一 OKHttp简介 OKHttp是一个处理网络请求的开源项目,Android 当前最火热网络框架,由移动支付Square公司贡献,用于替代HttpUrlConnection和Apache HttpC ...
- Linux启动时间优化-内核和用户空间启动优化实践
关键词:initcall.bootgraph.py.bootchartd.pybootchart等. 启动时间的优化,分为两大部分,分别是内核部分和用户空间两大部分. 从内核timestamp 0.0 ...
- 打包优化实践(如何Code Spliting)
项目地址:ReactSPA 使用 webpack 插件找出占用空间较大的包 开发环境中可使用 analyze-webpack-plugin 观察各模块的占用情况.以该项目为例:浏览器中输入 http: ...
- 三十、小程序解析HTML(对富文本返回数据的处理)
1.首先需要下载插件wxParse 下载地址 https://github.com/ZCLegendary/WXNews 百度云盘有保存 WXML <import src="../.. ...
- centos 6.8 搭建svn服务器
1. yum remove subversion #卸载 svn服务 2.下载svn服务器安装包 yum -y install subversion 3.创建SVN版本库 mkdir -p /opt/ ...
- MySQL数据类型的选择
+++++++++++++++++++++++++++++++++++++++++++标题:MySQL数据类型的选择时间:2019年2月22日内容:MySQL数据类型的选择范式参考重点:主要讲述MyS ...
- 家庭记账本小程序之增(java web基础版三)
实现新增消费账单 1.main_left.jsp中该部分,调用add.jsp 2. add.jsp,提交到Servlet的add方法 <%@ page language="java&q ...
- python 支付宝SDK
python 支付宝SDK代码如下 from datetime import datetime from Crypto.PublicKey import RSA from Crypto.Signatu ...