[python/35ms] With clear comments


  • 0
    class Solution(object):
        def compareVersion(self, version1, version2):
            """
            :type version1: str
            :type version2: str
            :rtype: int
            """
    
            # split two strings by '.' into a list of integer strings
            lv1 = version1.split('.')
            lv2 = version2.split('.')
        
            # compare all pairs of integers
            i = 0
            while i < min(len(lv1),len(lv2)):
                if int(lv1[i]) > int(lv2[i]):
                    return 1
                if int(lv1[i]) < int(lv2[i]):
                    return -1
                i += 1
        
            # now all the integer pairs are the same
            # but we still need to take care some corner cases
            if sum([int(x) for x in lv1[i:]])>0:
                # if version 1 is non-trivially longer than version 2
                # using sum(...) > 0 to rule out case such like '1.0' vs '1'
                return 1
            elif sum([int(x) for x in lv2[i:]])>0:
                # if version 2 is non-trivially longer than version 1
                return -1
            else:
                # if two versions are the "same"
                # "same": here we treat for instance '1.0.0.0' == '1'
                return 0

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.