需要考虑版本号比较长的情况
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 比较版本号
* @param version1 string字符串
* @param version2 string字符串
* @return int整型
*/
public int compare (String version1, String version2) {
// write code here
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int len = Math.max(str1.length, str2.length);
for (int i = 0; i < len; i++) {
String a = i < str1.length ? str1[i] : "0";
String b = i < str2.length ? str2[i] : "0";
for (int j = 0; j < a.length(); j++) {
if (j == a.length() - 1 || a.charAt(j) != '0') {
a = a.substring(j);
break;
}
}
for (int j = 0; j < b.length(); j++) {
if (j == b.length() - 1 || b.charAt(j) != '0') {
b = b.substring(j);
break;
}
}
if (a.length() > b.length()) {
return 1;
} else if (a.length() < b.length()) {
return -1;
} else {
if (a.compareTo(b) > 0) {
return 1;
} else if (a.compareTo(b) < 0) {
return -1;
}
}
}
return 0;
}
}