Leetcode[165] Compare Version Numbers
14 Nov 2015###Task1 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
###Python ####simple
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
li1 = version1.split('.')
li2 = version2.split('.')
if len(li1) > len(li2):
diff = len(li1) - len(li2)
while diff:
li2.append('0')
diff -= 1
else:
diff = len(li2) - len(li1)
while diff:
li1.append('0')
diff -= 1
for i in range(len(li1)):
if int(li1[i]) > int(li2[i]):
return 1
elif int(li1[i]) < int(li2[i]):
return -1
return 0
###Java
public class Solution {
public int compareVersion(String version1, String version2) {
if (version1 == null || version2 == null || version1.length() == 0 || version2.length() == 0) {
return 0;
}
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
int length1 = arr1.length;
int length2 = arr2.length;
if (length1 > length2) {
String[] extended1 = new String[length1];
String[] extended2 = new String[length1];
for (int i = 0; i < length1; i++) {
extended1[i] = arr1[i];
extended2[i] = i < length2 ? arr2[i] : "0";
}
for (int i = 0; i < length1; i++) {
if (Integer.parseInt(extended1[i]) > Integer.parseInt(extended2[i])) {
return 1;
}
if (Integer.parseInt(extended1[i]) < Integer.parseInt(extended2[i])) {
return -1;
}
}
} else if (length1 <= length2) {
String[] extended1 = new String[length2];
String[] extended2 = new String[length2];
for (int i = 0; i < length2; i++) {
extended2[i] = arr2[i];
extended1[i] = i < length1 ? arr1[i] : "0";
}
for (int i = 0; i < length2; i++) {
if (Integer.parseInt(extended1[i]) > Integer.parseInt(extended2[i])) {
return 1;
}
if (Integer.parseInt(extended1[i]) < Integer.parseInt(extended2[i])) {
return -1;
}
}
}
return 0;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.compareVersion("1", "1.1"));
}
}
###Points
- The point is really about how to split
- Make two lists the same length and then compare one by one