Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the .
character.
The .
character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5
is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
先贴上实现算法。
public int compareVersion(String version1, String version2) {
int sum1, sum2, i = 0, j = 0;
int len1 = version1.length();
int len2 = version2.length();
while (i < len1 || j < len2) {
sum1 = 0;
sum2 = 0;
while (i < len1 && version1.charAt(i) != '.')
sum1 += sum1 * 10 + version1.charAt(i++) - '0';
while (j < len2 && version2.charAt(j) != '.')
sum2 += sum2 * 10 + version2.charAt(j++) - '0';
if (sum1 > sum2)
return 1;
else if (sum1 < sum2)
return -1;
else {
i++;
j++;
}
}
return 0;
}
比如说比较版本号21.13.3与21.64.12,先比较大版本,得出相等结论,在比较次版本,也符合正常逻辑思维。
总结:
1、之前用split(".");的时候,并不能得到符合期望的结果,后来查询之后才发现。Java中,String类的split方法原型:public String[] split(String regex)根据给定的正则表达式的匹配来拆分此字符串,而 . 在正则表达式中指任何字符。
故应该采用split("\\.")来得到预期结果。
2、Pattern Matcher使用还是有点生疏。
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(str);
matcher.matches();
当然也可以这样使用:
str1.matches("[0-9]+");
关于Java正则表达式,可以参考下这篇博文。
http://blog.csdn.net/kofandlizi/article/details/7323863
转载请注明:@author:HoraceLi,purplefall@163.com