如 1.2.3a 和 1.2.4b
我写的方法,各位大大还有啥好的办法留言一下.
/**
* 这是个错误的方法,错误的错误的错误的错误的,某次面试面试官看我的博客说这个方法有问题,我回来思考了一下确实有问题大家不要参 *考方法 这个方法了。。留下错误的历史罪证。
* 编程实现一个比较任意两个软件版本号大小的函数,如 1.2.3a 和 1.2.4b
* 当opt1大于opt2时返回true,当opt1小鱼opt2时返回false
*
* @param opt1
* @param opt2
* @return
*/
public static boolean compare(String opt1, String opt2) {
byte[] bytes1 = opt1.getBytes();
byte[] bytes2 = opt2.getBytes();
int top = 0;
while (top < bytes1.length && top < bytes2.length) {
if (bytes1[top] > bytes2[top]) {
return true;
} else if (bytes1[top] < bytes2[top]) {
return false;
}
top++;
}
if (bytes1.length > bytes2.length) {
return true;
}
if (bytes1.length < bytes2.length) {
return false;
}
return false;
}
------------------------------------历史分割线------------------------------------------------------------------------------
这个方法我压测了一些例子,看看有没有小伙伴能够给出反例出来,
/**
* 比较字符串资源版本号算法。
* <pre>当同一个位置的时候出现数字和字母进行比较的时候我们默认字母号高于数字号。</pre>
* <p>
* 时间复杂度o(n)^2
*
* @param opt1 string 1
* @param opt2 string 2
* @return 当两个字符串相等的时候返回为0 ,当字符串1大于字符串2的时候返回1。
* 当字符串1小于字符串2的时候返回为-1
*/
private static int compare(@NotNull String opt1, @NotNull String opt2) {
if (opt1.hashCode() == opt2.hashCode()) {
return 0;
}
String[] array1 = opt1.split("\\.");
String[] array2 = opt2.split("\\.");
int length = array1.length > array2.length ? array2.length : array1.length;
for (int len = 0; len < length; len++) {
if (checkNum(array1[len]) && checkNum(array2[len])) {
int result = Integer.parseInt(array1[len]) - Integer.parseInt(array2[len]);
if (result == 0) continue;
return result > 0 ? 1 : -1;
} else {
String[] temp1 = subSplit(array1[len]);
String[] temp2 = subSplit(array2[len]);
int subLen = temp1.length > temp2.length ? temp2.length : temp1.length;
for (int i = 0; i < subLen; i++) {
boolean check1 = checkNum(temp1[i]);
boolean check2 = checkNum(temp2[i]);
if (check1 && check2) {
int result = Integer.parseInt(temp1[i]) - Integer.parseInt(temp2[i]);
if (result == 0) continue;
return result > 0 ? 1 : -1;
} else if (!check1 && !check2) {//纯单个字母比较
if (temp1[i].equals(temp2[i])) continue;
return temp1[i].compareTo(temp2[i]);
}
//数字和字符混合比较
if (check1) return -1;
if (check2) return 1;
}
if (temp1.length != temp2.length)
return temp1.length > temp2.length ? 1 : -1;
}
}
if (array1.length != array2.length)
return array1.length > array2.length ? 1 : -1;
return 0;
}
private static boolean checkNum(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
Matcher isNum = pattern.matcher(str);
return isNum.matches();
}
private static String[] subSplit(String str) {
StringBuilder number = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
number.append("|");
number.append(str.charAt(i));
number.append("|");
} else {
number.append(str.charAt(i));
}
}
return number.toString().split("\\|+");
}