Leetcode 165 Compare Version Numbers

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

将两个版本号码的字符串以点分隔的方式转换为数字放入数组,如果长度不相等则在短的后面补0,最后两数组逐个元素比较。

class Solution:
    # @param version1, a string
    # @param version2, a string
    # @return an integer
    def compareVersion(self, s1, s2):
        s1 += '.'
        s2 += '.'
        x1, x2 = [], []
        
        while s1 or s2:
            for i in range(len(s1)):
                if s1[i] == '.':
                    x1.append(int(s1[:i]))
                    break
            s1 = s1[i+1:]
            for i in range(len(s2)):
                if s2[i] == '.':
                    x2.append(int(s2[:i]))
                    break
            s2 = s2[i+1:]
            
        if len(x1) > len(x2):
            for i in range(len(x1)-len(x2)):
                x2.append(0)
        if len(x2) > len(x1):
            for i in range(len(x2)-len(x1)):
                x1.append(0)
        
        for i in range(len(x1)):
            if x1[i] > x2[i]:
                return 1
            if x2[i] > x1[i]:
                return -1
        return 0   

 

posted @ 2015-07-19 16:46  lilixu  阅读(152)  评论(0编辑  收藏  举报