-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompare_version_numbers.py
67 lines (61 loc) · 2.31 KB
/
compare_version_numbers.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
""" Problem description can be found here:
https://leetcode.com/problems/compare-version-numbers/description/
"""
class Solution:
def compareVersion(self, version1, version2):
""" Returns 1 if version1 newer than version2,
-1 if version1 older than version2,
0 if versions are the same.
Time complexity: O(n + m). Space complexity: O(1), where
m, n are the lengths of the strings version1, version2.
"""
i, j = 0, 0
n, m = len(version1), len(version2)
while i < n and j < m:
# find number in version1
num1 = 0
while i < n and version1[i] != ".":
num1 = num1 * 10 + int(version1[i])
i += 1
# find number in version2
num2 = 0
while j < m and version2[j] != ".":
num2 = num2 * 10 + int(version2[j])
j += 1
# compare current version numbers
if num1 > num2:
return 1
elif num1 < num2:
return -1
if i == n or j == m: # version1 or version2 is finished
break
else: # move on to the next number in version
i += 1
j += 1
# versions are the same so far, so
# check version numbers from longer version (if there's one)
# if any of the versions has additional numbers, current i / j is
# gonna be stopped at ".", so we increase it
i += 1
for x in range(i, n):
if version1[x] == ".":
continue
if version1[x] > "0": # version1 is higher
return 1
j += 1
for x in range(j, m):
if version2[x] == ".":
continue
if version2[x] > "0": # version2 is higher
return -1
return 0 # same versions
if __name__ == "__main__":
sol = Solution()
# tests
assert sol.compareVersion("1", "1") == 0
assert sol.compareVersion("1", "1.0.0.0.0") == 0
assert sol.compareVersion("1", "1.0.0.0.0") == 0
assert sol.compareVersion("1", "1.0.0.0.1") == -1
assert sol.compareVersion("1", "1.1") == -1
assert sol.compareVersion("1.0.0.0.1", "1.0.0") == 1
assert sol.compareVersion("3.6.2", "3.6.1") == 1