码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 165 Compare Version Numbers

时间:2015-07-19 17:53:13      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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   

 

Leetcode 165 Compare Version Numbers

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4658842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!