-4

假设我有一个版本号列表作为字符串

  • 2_1.1.1_release
  • 3-2_snapshot
  • 3.2.1 <---我想要的那个
  • 1.3(稳定)
  • 0.2(1_releaseCan)

每个版本都是一个 String 。我已经通过正则表达式将它们拆分,将它们保存到 String[]s 集合中我如何设计一个算法来找到最大的版本号?注意 3.2 小于 3.2.1 因为 3.2 等于 3.2.0 是的,任何缺失的数字都被视为 0

谢谢大家

4

3 回答 3

4

虽然不是最优的,但直截了当的解决方案

public class VersionComparator implements Comparator<String>  {

  public int compare(String version1, String version2) {
    // Split version into parts
    String parts1[] = getVersionParts(version1),
           parts2[] = getVersionParts(version2);

    // Go through common prefix left to right, first part which is higher indicates
    // higher version (4.2.1 > 4.2.0 > 3.9.9)
    for (int i = 0 ; i < Math.min(parts1.length, parts2.length); i++) {
      int partComparison = compareVersionPart(parts1[i], parts2[i]);
      if (partComparison != 0){
        return partComparison;
      }
    }

    // Common prefix is the same; longer value means higher version
    // (3.2.1 > 3.2)
    if (parts1.length > parts2.length) {
      return 1;
    } else if (parts1.length < parts2.length) {
      return -1;
    } else {
      return 0;
    }

  }

  protected String[] getVersionParts(String version) {
    return version.split("\\.");
  }

  protected int compareVersionPart(String part1, String part2) {
    int versionPart1 = Integer.parseInt(part1),
        versionPart2 = Integer.parseInt(part2);

    if (versionPart1 > versionPart2) {
      return 1;
    } else if (versionPart1 < versionPart2) {
      return -1;
    } else {
      return 0;
    }
  }

}

然后你做类似的事情Arrays.sort(versions, new VersionComparator())并选择最后一个元素。更新:Collections.max()会是更好的选择。

于 2012-05-27T15:39:39.663 回答
2

试试这个比较器:

private static final Comparator<String[]> comp = new Comparator<String[]>() {
    public int compare(String[] arg0, String[] arg1) {
        int length = arg0.length;
        if (arg1.length>arg0.length) length = arg1.length;

        for (int i=0; i<length; i++) {
            String s0 = null;
            if (i<arg0.length) s0 = arg0[i];
            Integer i0 = (s0==null)?0:Integer.parseInt(s0);
            String s1 = null;
            if (i<arg1.length) s1 = arg1[i];
            Integer i1 = (s1==null)?0:Integer.parseInt(s1);
            if (i0.compareTo(i1)<0) return -1;
            else if (i1.compareTo(i0)<0) return 1;
        }
        return 0;
    }
};

然后使用 arrays.sort() 方法: Arrays.sort(strings, comp);

于 2012-05-27T15:14:51.697 回答
0

比较器的算法是这样的:

public int compare(String a, String b) {
    Integer a1 = firstPart(a);
    Integer b1 = firstPart(b);

    int res = a1.compareTo(b1);

    if (res != 0) 
        return res;

    return compare(remainingParts(a), remainingParts(b));
}

您只需要实现firstPartremainingParts。然后,您可以使用Arrays.sort

于 2012-05-27T15:19:44.850 回答