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:

1
0.1 < 1.1 < 1.2 < 13.37

思路

题目其实不难,需要我们去比较版本号。

要注意,版本号和小数不同,可以是诸如major.minor(.build)这样的形式。其中,build号还可以用日期(如1.2.20170101来命名,另外,版本号的排序也有讲究。举例:

1.124 > 1.4 > 0.134 > 0.5 > 0.0.2 > 0.0.1

弄清楚以上的规律,代码也就好组织了。将所提供的字符串按照规则转换为可以比较的形式即可。在代码中,我利用了list对圆点隔开的每一个数进行存储,从而也可以比较版本号。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1 = []
v2 = []
tmp = ""
for i in version1:
if (i == "."):
v1.append(int(tmp))
tmp = ""
else:
tmp += i
v1.append(int(tmp))
tmp = ""
for j in version2:
if (j == "."):
v2.append(int(tmp))
tmp = ""
else:
tmp += j
v2.append(int(tmp))
while (len(v1) and v1[-1] == 0):
del v1[-1]
while (len(v2) and v2[-1] == 0):
del v2[-1]
len1 = len(v1)
len2 = len(v2)
for i in range(min(len1,len2)):
if (v1[i] > v2[i]):
return 1
elif (v1[i] < v2[i]):
return -1
if (len1 == len2):
return 0
elif (len1 > len2):
return 1
else:
return -1