public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 比较版本号
* @param version1 string字符串
* @param version2 string字符串
* @return int整型
*/
public int compare (String version1, String version2) {
// write code here
if (version1 == null && version2 == null) {
return 0;
} else if (version2 == null && version2 != null) {
return -1;
} else if (version1 != null && version2 == null) {
return 1;
} else if (version1.equals(version2)) {
return 0;
}
String[] part1 = version1.split("\\.");
String[] part2 = version2.split("\\.");
int i = 0, j = 0;
int max = Math.max(part1.length, part2.length);
for (int k = 0; k < max; k++) {
String str1 = i < part1.length ? part1[i++] : "0";
String str2 = j < part2.length ? part2[j++] : "0";
int diff = Math.abs(str1.length() - str2.length());
if (str1.length() < str2.length()) {
str1 = getZero(diff) + str1;
} else if (str1.length() > str2.length()) {
str2 = getZero(diff) + str2;
}
int res = str1.compareTo(str2);
if (res != 0) {
return res > 0 ? 1 : -1;
}
}
return 0;
}
private String getZero(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append("0");
}
return sb.toString();
}
}