Monday, August 24, 2015

Leetcode 165. Compare Version Numbers

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

The problem itself is not very hard, but how to deal with extra zeros? Of course we can add a sentence to judge if the remaining part is all zeros, while the better way is to fill zeros before hand to make the two strings have the same length.

Solution:
# T:O(n) S:O(n)
class Solution:
    # @param a, a string
    # @param b, a string
    # @return a boolean
    def compareVersion(self, version1, version2):
        v1, v2 = version1.split("."), version2.split(".")
        
        if len(v1) > len(v2):
            v2 += ['0' for _ in xrange(len(v1) - len(v2))]
        elif len(v1) < len(v2):
            v1 += ['0' for _ in xrange(len(v2) - len(v1))]
        
        i = 0
        while i < len(v1):
            if int(v1[i]) > int(v2[i]):
                return 1
            elif int(v1[i]) < int(v2[i]):
                return -1
            else:
                i += 1
        
        return 0
Run Time: 56 ms

No comments:

Post a Comment