版权声明:本文章为博主原创,转载请注明出处。保留所有权利。

Contents
  1. 1. 题目
  2. 2. 解析

Leetcode-165的解题过程。

  • 题目

    Compare two version numbers version1 and version2.
    If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

    You may assume that the version strings are non-empty and contain only digits and the . character.
    The . character does not represent a decimal point and is used to separate number sequences.
    For instance, 2.5 is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.

    Here is an example of version numbers ordering:

    1
    0.1 < 1.1 < 1.2 < 13.37
  • 解析

      比较版本号的大小。通常来说版本号的格式一般是用小数点隔开的若干数字,同时左侧的数字级别要高过右侧的数字。和普通的小数不同的是,版本号中可能包括多个小数点,并且小数点之间的数字表示的意义和正常的小数不同。例如,若版本A的版本号为1.7,则代表的意义为:A是一级版本“1”下的第“7”个二级版本,同理,如果版本B的版本号为1.12,说明B是一级版本“1”下的第“12”个二级版本,那么显然是有A<B的。
      因此,比较版本号时应当按照小数点分隔的各级版本号,从左至右依次进行比较。当两个版本号在同一级别上的数字不相同时,就可以分辨出版本号的大小。当然,两个版本号的“长度”,即他们所包含的级别数不一定相同,比较时应当注意。例如,版本号“1.1.1”应当大过版本号“1.1”。
      另外要注意的一点是“.0”这种形式的数字。例如,版本号“1”和“1.0”,甚至是“1.0.0”都应该是相等的。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    class Solution(object):
    def compareVersion(self, version1, version2):
    """
    :type version1: str
    :type version2: str
    :rtype: int
    """
    if version1 == version2:
    return 0
    v1 = version1.split('.')
    v2 = version2.split('.')
    count = 0
    for vv1,vv2 in zip(v1,v2):
    if int(vv1)>int(vv2):
    return 1
    elif int(vv1)<int(vv2):
    return -1
    count+=1
    # v1的“长度”大于v2时,如果v1长出来的部分里包括非0数字,则说明v1>v2
    if len(v1)>len(v2):
    for vv1 in v1[count:]:
    if int(vv1)!=0:
    return 1
    return 0
    elif len(v1)<len(v2):
    for vv2 in v2[count:]:
    if int(vv2)!=0:
    return -1
    return 0
    else:
    return 0

打赏

取消
扫码支持

你的支持是对我最好的鼓励

Contents
  1. 1. 题目
  2. 2. 解析