当前位置:网站首页>Comparison version number of middle questions in LeetCode
Comparison version number of middle questions in LeetCode
2022-08-10 12:56:00 【·The sea of stars】
题目
给你两个版本号 version1 和 version2 ,请你比较它们.
版本号由一个或多个修订号组成,各修订号由一个 ‘.’ 连接.每个修订号由 多位数字 组成,可能包含 前导零 .每个版本号至少包含一个字符.修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推.例如,2.5.33 和 0.1 都是有效的版本号.
比较版本号时,请按从左到右的顺序依次比较它们的修订号.比较修订号时,只需比较 忽略任何前导零后的整数值 .也就是说,修订号 1 和修订号 001 相等 .如果版本号没有指定某个下标处的修订号,则该修订号视为 0 .例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1 ,0 < 1 .
返回规则如下:
如果 version1 > version2 返回 1,
如果 version1 < version2 返回 -1,
除此之外返回 0.
示例 1:
输入:version1 = “1.01”, version2 = “1.001”
输出:0
解释:忽略前导零,“01” 和 “001” 都表示相同的整数 “1”
示例 2:
输入:version1 = “1.0”, version2 = “1.0.0”
输出:0
解释:version1 没有指定下标为 2 的修订号,即视为 “0”
示例 3:
输入:version1 = “0.1”, version2 = “1.1”
输出:-1
解释:version1 中下标为 0 的修订号是 “0”,version2 中下标为 0 的修订号是 “1” .0 < 1,所以 version1 < version2
提示:
1 <= version1.length, version2.length <= 500
version1 和 version2 仅包含数字和 ‘.’
version1 和 version2 都是 有效版本号
version1 和 version2 的所有修订号都可以存储在 32 位整数 中
来源:力扣(LeetCode)
解题思路
For the comparison of version numbers, the first point is to do a good job of point sum0的处理,在这道题中,You can first separate the overall version number with a dot,Compare from high to low.In the process of comparison, different analyses should be carried out for different situations,If the size can be compared in the high bit, the result will be returned directly,If it fails to separate the size in the high order,Then you need to observe which subsequent version number is longer,For long version numbers,requires further analysis,If there is more than in the tail0的数字,The longer version number is naturally larger,If the tails are0The two version numbers are the same.
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1=version1.split('.')
v2=version2.split('.')
for i,j in zip(v1,v2):
if int(i)>int(j):
return 1
elif int(i)<int(j):
return -1
if len(v1)>len(v2):
for i in v1[len(v2):]:
if int(i)>0:
return 1
return 0
elif len(v1)<len(v2):
for i in v2[len(v1):]:
if int(i)>0:
return -1
return 0
else:
return 0
边栏推荐
猜你喜欢
随机推荐
A detailed explanation of implementation api embed
Accumulated and thin hair!Safety Dog has once again obtained the certification of scientific and technological achievements transformation!
Overseas media publicity. What problems should domestic media pay attention to?
Drive IT Modernization with Low Code
LT8911EXB MIPI CSI/DSI转EDP信号转换
爱可可AI前沿推介(8.10)
IDC第一的背后,阿里云在打造怎样的一朵“视频云”?
wirshark 常用操作及 tcp 三次握手过程实例分析
bat脚本——提取多个文件夹到指定路径
技术人必看!数据治理是什么?它对数据中台建设重要吗?
CodeForces - 628D (digital dp)
Polygon zkEVM工具——PIL和CIRCOM
Is there a problem with the CURRENT_TIMESTAMP(6) function?
Alibaba Cloud Jia Zhaohui: Cloud XR platform supports Bizhen Technology to present a virtual concert of national style sci-fi
Codeforces Round #276 (Div. 1) D. Kindergarten
讯飞创意组别 全国选拔赛成绩公布说明
LeetCode中等题之搜索二维矩阵
来看Prada大秀吗?在元宇宙里那种!
48 the mysql database
把相亲角搬到海外,不愧是咱爸妈