Compare two version numbers version1 and version1. 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
這道題的意思用一個例子說明就是1.2 < 1.10, 由於1.10跟1.1是不同的,1.10表明tenth revision. 而1.1表明first revision。因此這道題要按「.」分段,而後分段比較,方法是用split函數把string 分段,每一段挨個比過去。這裏參考了網上的一個小技巧:git
因爲兩串字符串並非同樣長度的,若是分狀況比較,如第一個長,遍歷逐一比較則要分狀況討論。此時就採起一些小技巧,將兩個字符串對齊,就無需考慮各類狀況,超出的位數補0便可,這是一種字符串、數串比較的小技巧。好比比較 1 和 1.0正則表達式
因此這裏取了兩個string長度的最大值 maxLen, 來創建兩個數組來存split「.」以後分出來的數字,短的那個數組末尾默認補0. 而後從左到右挨個比過去express
Integer.parseInt()函數能將「012」轉化爲12,解決了首位爲0的問題數組
另外用split函數有一點特別要注意:咱們知道,「 . 」在正則表達式中有特殊的含義,所以咱們使用的時候必須進行轉義。less
不轉義就會有以下結果:ide
String ipstring="59.64.159.224"; 函數
String iparray[]=ipstring.split("."); spa
for(String stemp:iparray){ code
System.out.println(stemp); three
}
這個輸出爲空,爲何呢?
public string[] split(string regex) 這裏的參數的名稱是regex ,也就是 regular expression (正則表達式)。
「 . 」在正則表達式中有特殊的含義,表示means "any character" in regex
因此若是就想表示一個點的話,use either split("\\.")
or split(Pattern.quote("."))
.
1 public class Solution { 2 public int compareVersion(String version1, String version2) { 3 String[] strs1 = version1.split("\\."); 4 String[] strs2 = version2.split("\\."); 5 int maxLen = Math.max(strs1.length, strs2.length); 6 int[] nums1 = new int[maxLen]; 7 int[] nums2 = new int[maxLen]; 8 for (int i=0; i<strs1.length; i++) { 9 nums1[i] = Integer.parseInt(strs1[i]); 10 } 11 for (int i=0; i<strs2.length; i++) { 12 nums2[i] = Integer.parseInt(strs2[i]); 13 } 14 for (int i=0; i<maxLen; i++) { 15 if (nums1[i] > nums2[i]) return 1; 16 else if (nums1[i] < nums2[i]) return -1; 17 } 18 return 0; 19 } 20 }
Improve a lit bit by using less memory
1 public int compareVersion(String version1, String version2) { 2 String[] levels1 = version1.split("\\."); 3 String[] levels2 = version2.split("\\."); 4 5 int length = Math.max(levels1.length, levels2.length); 6 for (int i=0; i<length; i++) { 7 Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0; 8 Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0; 9 int compare = v1.compareTo(v2); 10 if (compare != 0) { 11 return compare; 12 } 13 } 14 15 return 0; 16 }