[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
相关推荐
Jerry40 分钟前
LeetCode 707. 设计链表
算法
C语言小火车1 小时前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序
kebidaixu1 小时前
两轮BMS AFE SH367306 I2C 读写时序
算法
智能排队系统_头部供应商1 小时前
RK3588边缘网关改造银行排队系统实战
算法
Fabarta1 小时前
从 0 实现 ChatGPT 风格的流式对话 UI
算法·架构
手写码匠2 小时前
手写 AI 上下文压缩系统:从零实现 Prompt 压缩与选择性上下文管理
人工智能·深度学习·算法·aigc
EAI-Robotics2 小时前
机器人操作鲁棒性:当机械手遇上真实世界的不确定性
人工智能·算法·机器人
shushangyun_3 小时前
2026智能采购商城系统选型指南:如何引领企业数字化采购升级
java·大数据·数据库·人工智能·机器学习
她说..3 小时前
Java 默认值设置方式
java·开发语言·后端·springboot
学渣超3 小时前
记一次分布式事务数据不一致的排查之旅:从超时到索引,层层剥茧
java·后端·架构