forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompareVersionNumbers.java
51 lines (40 loc) · 1.23 KB
/
CompareVersionNumbers.java
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
// O(n) , where n => no of elements in the version part
// O(1), space complexity
class CompareVersionNumbers {
public int compareVersion(String version1, String version2) {
String[] version1List = version1.split("\\."); // Note your cant directly use split(".") because if will treat he regex as any character
String[] version2List = version2.split("\\.");
int s1 = 0;
int s2 = 0;
int len1 = version1List.length;
int len2 = version2List.length;
while(s1<len1 && s2<len2){
int val1 = Integer.parseInt(version1List[s1]);
int val2 = Integer.parseInt(version2List[s2]);
s1++;
s2++;
if(val1>val2){
return 1;
} else if(val1<val2){
return -1;
} else{
// continue
}
}
while(s1<len1){
int val1 = Integer.parseInt(version1List[s1]);
s1++;
if(val1>0){
return 1;
}
}
while(s2<len2){
int val2 = Integer.parseInt(version2List[s2]);
s2++;
if(val2>0){
return -1;
}
}
return 0;
}
}