[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
相关推荐
程序员黑豆6 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
GreenTea6 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
风流 少年6 小时前
Spring AI 2.0:Memory
java·后端·spring
码匠许师傅7 小时前
【C++ 面试真题】聊聊 C++ 的移动语义与右值引用
java·c++·面试
小席是个热心肠7 小时前
AI相关的自我学习
java·人工智能·学习
fqq37 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
数智化管理手记10 小时前
海量数据如何沉淀有效数据资产?数据标准化治理方案如何搭建?
java·大数据·人工智能
半夏微凉半夏殇10 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
2501_9065651210 小时前
数学之美探究
算法
oier_Asad.Chen10 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环