[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
相关推荐
Jerry1 天前
LeetCode 189. 轮转数组
算法
Jerry1 天前
LeetCode 739. 每日温度
算法
是小蟹呀^1 天前
Spring Security + JWT 面试题整理
java·jwt·springsecurity
2601_954526751 天前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
spencer_tseng1 天前
Redis + Nacos.bat
java·windows·dos
troyzhxu1 天前
列表查询的 GraphQL —— 一行代码终结你的 if-else 地狱!
java·springboot·graphql
叩码以求索1 天前
浅谈:算法萌新如何高效刷题应对面试(一)
算法·面试·职场和发展
孫治AllenSun1 天前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
c238561 天前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法