[165] Compare Version Numbers

1. 題目描述

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

給定兩個使用“.”分割的版本號,實現comparable接口(相當於)。

2. 解題思路

首先給定兩個版本號,那麼什麼情況下版本號a.b.c大於版本號d.e呢,那麼就是哪個在前的數字大哪個版本號就大,考慮兩個版本號,首先將字符串進行分割,之後將分割的字符串轉換爲數字。一直比較到長度比較短的版本號結束,這時,如果前面有大小的區分,就已經有結果了,如果比較到短的串的最後一位還沒有結果,那麼看比較長的串後面是不是全0,當前Code是將String轉換爲了int,後來覺得是不是判斷一下是不是equals(“0”)就好,但是事實證明變態的測試用例不是這樣玩的,測試用例給定的版本號不一定是一個正常的數字,有可能是01,000之類的串,所以目前想到的就是轉換成int啦。

3. Code

public class Solution {
    public int compareVersion(String version1, String version2) {
        // 將String分割爲若干字符串
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        for(int i = 0; i < Math.min(v1.length, v2.length); ++i)
        {
            // 將String解析爲int
            int num1 = Integer.parseInt(v1[i]);
            int num2 = Integer.parseInt(v2[i]);
            // 如果兩個值不相等,v1>v2返回1,否則返回-1
            if(num1 != num2) return num1 > num2 ? 1 : -1;
        }
        // 如果兩個串長度相等,返回相等
        if(v1.length == v2.length) return 0;
        // 如果長度不等,長度長的那個大(×) 有可能是a.b.c.0.0.00.0
        for(int j = Math.min(v1.length, v2.length); j < Math.max(v1.length, v2.length); ++j)
        {
            if(v1.length > v2.length)
            {
                int num = Integer.parseInt(v1[j]);
                if(num != 0) return 1;
            }
            else if(v2.length > v1.length)
            {
                int num = Integer.parseInt(v2[j]);
                if(num != 0) return -1;
            }
        }
        return 0;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章