leetcode笔记--Compare Version Numbers

题目:难度(Easy)

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:
0.1 < 1.1 < 1.2 < 13.37
Tags:String

分析:比较版本串,要考虑的有:1.2个串可能不等长,那自然是版本串的最前面的版本数字是”高位“,后面的是”低位“,比较时先比较”高位“能更早得出结论。不等长的版本串也可能”相等“,例如”1.2“与”1.2.0“。

代码实现:

class Solution(object):
    def compareVersion(self, version1, version2):
        """
        :type version1: str
        :type version2: str
        :rtype: int
        """
        #将字符串拆分开并转化成int放到数组里
        v1 = map(int, version1.split("."))
        v2 = map(int, version2.split("."))
        #为较短的list的末尾填充0,方便后面的比较
        if len(v1) > len(v2):
            length = len(v1)
            i = len(v2)
            while i < length:
                v2.append(0)
                i += 1
        else:
            length = len(v2)
            i = len(v1)
            while i < length:
                v1.append(0)
                i += 1
        
        i = 0
        while i < length:
            if v1[i] > v2[i]:
                return 1
            elif v1[i] < v2[i]:
                return -1
            else:
                i += 1
        if i == length:
            return 0


你可能感兴趣的:(LeetCode,String)