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
问题描述:给出两个版本数字version1和version2,If version1 > version2 返回 1, if version1 < version2 返回 -1, otherwise 返回 0.
我们可以假设,给出的字符串时非空并且只会包含数字和“.”。版本比较规则如上所示。
问题分析:版本字符串的比较以.为分隔符,一次从左往右比较,如果当前位置的数字相同,则比较下一位,如果到最后一直相同说明两个版本号相等。当两个字符串中包含的.的数目不相等时,则以多的为准则,少的当前位置为0.
问题解答:
public class Solution { public int compareVersion(String version1, String version2) { String[] str1 = version1.split("\."); String[] str2 = version2.split("\."); int l = str1.length>str2.length?str1.length:str2.length; int[] s1 = new int[l]; int[] s2 = new int[l]; for(int i=0; i<l; i++){ if(i<str1.length) s1[i] = Integer.parseInt(str1[i]); if(i<str2.length) s2[i] = Integer.parseInt(str2[i]); } for(int i=0; i<l; i++){ if(s1[i]>s2[i]) return 1; if(s1[i]<s2[i]) return -1; } return 0; } }
解法二:与一略有不同,第一种方法是以长度达的字符串为准。如果两个字符串的长度差别很大则容易造成空间的浪费(短字符串将有很多0元素)
public class Solution { public int compareVersion(String version1, String version2) { String[] str1 = version1.split("\."); String[] str2 = version2.split("\."); int l = str1.length<str2.length?str1.length:str2.length; //取长度较小的 int[] s1 = new int[l]; int[] s2 = new int[l]; for(int i=0; i<l; i++){ //如果在相同长度内可以比较出版本号的大小 if(i<str1.length) s1[i] = Integer.parseInt(str1[i]); if(i<str2.length) s2[i] = Integer.parseInt(str2[i]); } for(int i=0; i<l; i++){ System.out.println("s2[]"+i+" "+s2[i]); if(s1[i]>s2[i]) return 1; if(s1[i]<s2[i]) return -1; } if(str1.length<str2.length && !str2[str1.length].equals("0")) //如果还未比较出大小,则长度大的版本号大。要注意的是多出来的那一位是0 return -1; else if(str1.length>str2.length && !str1[str2.length].equals("0")) return 1; else return 0; } }