Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.
Return the following:
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
Example 1:
Input: version1 = “1.01”, version2 = “1.001”
Output: 0
Explanation: Ignoring leading zeroes, both “01” and “001” represent the same integer “1”.
Example 2:
Input: version1 = “1.0”, version2 = “1.0.0”
Output: 0
Explanation: version1 does not specify revision 2, which means it is treated as “0”.
Constraints:
1 <= version1.length, version2.length <= 500
version1 and version2 only contain digits and '.'.
version1 and version2 are valid version numbers.
All the given revisions in version1 and version2 can be stored in a 32-bit integer.
简单来说,类似实现了一个Comparator的接口,要实现里面的compare函数,也就是自定义比大小。
把带有".“的版本号以”."分割开,从左到右比较每段数字的大小,
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
思路:
以“.“把字符串分割开,比较每段的数字大小。
注意不能直接split(”."),一定要用转义字符"\\."。
那如果version1分割后的长度 < version2的长度怎么办,在version2多出来的那段里面,设version1参与比较的数字都是0,去和version2的数字比即可,反之亦然。
分割出的每段String数字,可以用十进制法把String转换成数字,这里直接用Integer.parseInt函数转。
public int compareVersion(String version1, String version2) {
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int i = 0;
int n1 = str1.length;
int n2 = str2.length;
int num1 = 0;
int num2 = 0;
while(i < n1 || i < n2) {
if(i < n1) num1 = Integer.parseInt(str1[i]);
if(i < n2) num2 = Integer.parseInt(str2[i]);
if(num1 < num2) {
return -1;
} else if(num1 > num2) {
return 1;
}
i ++;
num1 = 0;
num2 = 0;
}
return 0;
}