Compare two version numbers version1 and version1.
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题本身没什么意思,比较脑洞的出题人给出的测试样例会出现类似12.3.4.5.0.0.000.0.00.00.0.00.0.0.0.0.00000的情况
做题中发现在String类的split方法使用的是正则表达式,因而会产生歧义的符号需要转义,比如这里的" . "(点)
代码
public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
for (int i = 0; i < Math.max(v1.length, v2.length); i++) {
int gap = (i < v1.length ? Integer.parseInt(v1[i]) : 0) - (i < v2.length ? Integer.parseInt(v2[i]) : 0);
if (gap != 0) {
return gap > 0 ? 1 : -1;
}
}
return 0;
}
本想考虑减少比较次数,在其中一个较短字符串比较完之后,另一较长字串剩下的直接转化为整型值判断是否为零,结果出了一个耗时更长的结果,方法肯定有的这儿就先不做了
import java.util.Scanner;
//compare version numbers 680ms
public class CVN2 {
public static int compareVersion(String version1, String version2) {
Scanner s1 = new Scanner(version1);
Scanner s2 = new Scanner(version2);
s1.useDelimiter("\\.");
s2.useDelimiter("\\.");
int a,b;
while(s1.hasNextInt()&&s2.hasNextInt()){
a = s1.nextInt();
b = s2.nextInt();
if(a>b)return 1;
else if(a<b)return -1;
else continue;
}
if(s1.hasNextInt()){
s1.useDelimiter(" ");
if(Integer.parseInt(s1.nextLine().toString().replaceAll("\\.",""))==0)return 0;
else return 1;
}
if(s2.hasNextInt()){
s2.useDelimiter(" ");
if(Integer.parseInt(s2.nextLine().toString().replaceAll("\\.",""))==0)return 0;
else return -1;
}
return 0;
}
public static void main(String[] args){
String v1;
String v2;
v1="1.0";
v2="1";
System.out.println(compareVersion(v1,v2));
}
}
发现Scanner类反倒更耗时,不是一个好办法