[leetcode] 165. Compare Version Numbers

Description

Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.

To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.

Return the following:

  • If version1 < version2, return -1.
  • If version1 > version2, return 1.
  • Otherwise, return 0.

Example 1:

复制代码
Input: version1 = "1.2", version2 = "1.10"
Output: -1

Explanation:

version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.

Example 2:

复制代码
Input: version1 = "1.01", version2 = "1.001"

Output: 0

Explanation:

Ignoring leading zeroes, both "01" and "001" represent the same integer "1".

Example 3:

复制代码
Input: version1 = "1.0", version2 = "1.0.0.0"

Output: 0

Explanation:

version1 has less revisions, which means every missing revision are treated as "0".

Constraints:

  • 1 <= version1.length, version2.length <= 500
  • version1 and version2 only contain digits and '.'.
  • version1 and version2 are valid version numbers.
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.

分析

思路就是按照句号隔开,然后逐个比较。

Python

python 复制代码
class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        n1 = len(version1)
        n2 = len(version2)
        i= 0
        j=0 
        while i<n1 or j<n2:
            val1 = 0
            while i<n1 and version1[i]!='.':
                val1=val1*10+int(version1[i])
                i+=1
            val2 = 0
            while j<n2 and version2[j]!='.':
                val2 = val2*10+int(version2[j])
                j+=1
            if val1<val2:
                return -1
            elif val1>val2:
                return 1
            i+=1
            j+=1
        return 0
相关推荐
砍材农夫1 小时前
物联网实战|Spring Boot + Netty 搭建 MQTT 消息路由与流转层
java·spring boot·后端·物联网·spring
装不满的克莱因瓶2 小时前
掌握语义分割经典模型 FCN——从像素分类到端到端分割的奠基之作
人工智能·python·深度学习·算法·机器学习·分类·数据挖掘
黄毛火烧雪下2 小时前
Java 基础笔记:文件、递归与字符编码
java·开发语言·笔记
学计算机的计算基2 小时前
链表算法上篇:LeetCode 206/234/141/142/160/21 题解与易错点
java·笔记·算法·链表
信也科技布道师2 小时前
从Istio 503 NC 错误深入理解 Mesh 路由全链路原理
java·服务器·网络
大白话_NOI2 小时前
【洛谷 P2678】 [NOIP2015 提高组] 跳石头 超详细题解
c++·算法
swordbob2 小时前
3 大 I/O 模型BIO / NIO / AIO
java·linux·spring
xwz小王子2 小时前
ICRA 2026深度观察:全栈闭环成标配,中国具身智能势力显著崛起
大数据·人工智能·算法
Pluto_CSND2 小时前
Cron表达式使用说明
java