Leetcode P0165"Compare Version Numbers" 题解

2020/09/22 Leetcode

博文中会简要介绍Leetcode P0165题目分析及解题思路。

“Compare Version Numbers”是一道比较简单的题目,这道题属于“看题编程”类型,即模拟一遍题目要求的过程即可。

Given two version numbers, version1 and version2, compare them.

Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

Return the following:

  • If version1 < version2, return -1.
  • If version1 > version2, return 1.
  • Otherwise, return 0.

主要思路就是,将给定的版本字符串分割,然后每一个版本号进行比较,最终得到版本号之间的大小关系。

以下是Java的题解代码实现。

class Solution {
    public int compareVersion(String version1, String version2) {
        String[] version1s = version1.split("\\.");
        String[] version2s = version2.split("\\.");
        
        int L1 = version1s.length, L2 = version2s.length;
        
        int len = Math.max(L1, L2);
        
        for (int idx=0; idx<len; ++idx) {
            int revision1 = (idx < L1)? Integer.parseInt(version1s[idx]): 0;
            int revision2 = (idx < L2)? Integer.parseInt(version2s[idx]): 0;
            
            if (revision1 < revision2)
                return -1;
            else if (revision1 > revision2)
                return 1;
        }
        
        return 0;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int compareVersion(string version1, string version2) {
        vector<string> revisions1;
        this->_Split(version1, '.', revisions1);
        
        vector<string> revisions2; 
        this->_Split(version2, '.', revisions2);
        
        int L1 = revisions1.size(), L2 = revisions2.size();
        int len = max(L1, L2);
        
        for (int idx=0; idx<len; ++idx) {
            int revision1 = (idx < L1)? stoi(revisions1[idx]): 0;
            int revision2 = (idx < L2)? stoi(revisions2[idx]): 0;
            
            if (revision1 > revision2)
                return 1;
            else if (revision1 < revision2)
                return -1;
        }
        
        return 0;
    }
    
private:
     void _Split(const string s, char delim, vector<string> &parts) {
        stringstream ss(s);
        string part;
        while (getline(ss, part, delim)) {
            parts.push_back(part);
        }
    }
};

Search

    Table of Contents