165. 比较版本号

https://leetcode-cn.com/problems/compare-version-numbers/

解法一:字典序比较

先将字符串转换成字符数组,再转换成整数list,用python自带的比较运算即可实现字典序判断。

#list比较运算,逐次比较第0,1,2,...位
>>> [1,2,3] > [1,2,1]  #长度相等
True
>>> [1,2,3] > [1,2,3,0]  #长度不想等
False

一些难通过的case是小数点位置不对齐,如"1.0" "1",或者"0010.0" "00010",切分出来导致结果错误。解决办法是统一填充预处理,使其小数点数都相等。

class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        #计算两者的点号数量
        points1 = version1.count('.')
        points2 = version2.count('.')
        #求差
        diff = points1 - points2
        #将点号少串的补0,使之与点号较多的串对齐
        if diff > 0:
            for _ in range(diff):
                version2 += '.0'
        elif diff < 0:
            for _ in range(-diff):
                version1 += '.0'
        #调用函数转换
        ver1 = self.convert(version1)
        ver2 = self.convert(version2)
        #数组直接比较
        if ver1 > ver2:
            return 1
        elif ver1 < ver2:
            return -1
        else:
            return 0
    
    #转换函数
    def convert(self, str):
        chs = str.split('.')  #字符串按'.'号切分
        res = []  #输出
        for ch in chs:  #将每个字符转成int
            res.append(int(ch))
        return res

最后更新于