Problem: 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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Solution: Compare Version Numbers, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-02-11 23:25:39
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @param version1, a string
# @param version2, a string
# @return an integer
def compareVersion(self, version1, version2):
v1 = map(int, version1.split("."))
v2 = map(int, version2.split("."))
v1.extend([0] * (len(v2) - len(v1)))
v2.extend([0] * (len(v1) - len(v2)))
return 0 if v1 == v2 else {True: 1, False: -1}[v1 > v2]

用 Python 实现起来很优雅。一般思路是:用 “.” 分割代表版本信息的字符串,将每个版本信息字符串分割后的子串强转为 int ,得到一个数组。两个版本字符串比较时,同时遍历两个数组,对数组元素进行判断。