Leetcode 165. Compare Version Numbers

Problem

Given two version numbers, version1 and version2, compare them.

Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

Return the following:

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

Algorithm

Divid each part and compare the value.

Code

class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        p1, p2, L1, L2 = 0, 0, len(version1), len(version2)
        while p1 < L1 or p2 < L2:
            v1 = 0
            while p1 < L1 and version1[p1] >= '0' and version1[p1] <= '9':
                v1 = v1 * 10 + ord(version1[p1]) - ord('0')
                p1 += 1
            while p1 < L1 and (version1[p1] < '0' or version1[p1] > '9'):
                p1 += 1
            v2 = 0
            while p2 < L2 and version2[p2] >= '0' and version2[p2] <= '9':
                v2 = v2 * 10 + ord(version2[p2]) - ord('0')
                p2 += 1
            while p2 < L2 and (version2[p2] < '0' or version2[p2] > '9'):
                p2 += 1
            if v1 > v2:
                return 1
            elif v1 < v2:
                return -1
        return 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值