Skip to content

Commit 310637a

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
compare version number
1 parent fbb7785 commit 310637a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

compare-version-numbers.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
i1 and i2 is the pointer we point to the starting point.
3+
Character before i1 and i2 we already processed.
4+
When they are set to -1, the whole string are already processed.
5+
6+
#for-loop can't find the '.' any more. [0]
7+
8+
after two version is fully processed and couldn't find which is larger, return 0. [1]
9+
10+
Time Complexity is O(N).
11+
N is the length of those version, because we potentially loop through them once.
12+
13+
Space Complexity is O(1).
14+
Because we only store two pointers and two integer.
15+
"""
16+
class Solution(object):
17+
def compareVersion(self, version1, version2):
18+
def getVersion(version, start):
19+
if start==-1: return 0, -1
20+
for i in xrange(start, len(version)):
21+
if version[i]=='.':
22+
return int(version[start:i]), i+1
23+
return int(version[start:]), -1 #[0]
24+
25+
i1 = i2 = 0
26+
27+
while True:
28+
sub_version1, i1 = getVersion(version1, i1)
29+
sub_version2, i2 = getVersion(version2, i2)
30+
31+
if sub_version1>sub_version2:
32+
return 1
33+
elif sub_version1<sub_version2:
34+
return -1
35+
elif i1==-1 and i2==-1: #[1]
36+
return 0

0 commit comments

Comments
 (0)