165. 比较版本号
注意事项:
- 注意用split的时候里面分的是正则表达。因此点为"\."
- 字符串的compareTo不一定是0,-1,1.
自己做的是逐级比较,并且去掉首部分的零。代码如下:
public static int compareVersion(String version1, String version2) {
String[] split1 = version1.split("\\.");
String[] split2 = version2.split("\\.");
int min = Math.min(split1.length, split2.length);
for(int i=0; i<min; i++) {
int compare = compare(split1[i], split2[i]);
if(compare != 0) {
return compare;
}
}
String[] temp;
int result = 0;
if(min == split1.length) {
temp = split2;
result = -1;
} else {
temp = split1;
result = 1;
}
for (int i = min; i < temp.length; i++) {
if(!trim(temp[i]).equals("0")) {
return result;
}
}
return 0;
}
public static int compare(String s1, String s2) {
s1 = trim(s1);
s2 = trim(s2);
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
public static String trim(String s) {
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j) != '0') {
return s.substring(j);
}
}
return "0";
}
public static void main(String[] args) {
System.out.println(compareVersion("1.05", "1.1"));
}
image.png
别人解法容易很多,parseInt可以去掉上面的0;
public int compareVersion(String v1, String v2) {
String[] ss1 = v1.split("\\."), ss2 = v2.split("\\.");
int n = ss1.length, m = ss2.length;
int i = 0, j = 0;
while (i < n || j < m) {
int a = 0, b = 0;
if (i < n) a = Integer.parseInt(ss1[i++]);
if (j < m) b = Integer.parseInt(ss2[j++]);
if (a != b) return a > b ? 1 : -1;
}
return 0;
}
网友评论