版本比較

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:如果兩個(gè)版本長(zhǎng)度不一樣怎么辦
2:版本后綴為0的情況

#include <string>
#include <vector>
#include <algorithm>
using namespace std;


class Solution {
public:
    void SplitNumber(vector<int> &versionNumVec, string version){
        int index = version.find('.');
        while (index != string::npos){
            versionNumVec.push_back(stoi(version.substr(0, index)));
            version = version.substr(index + 1);
            index = version.find('.');
        }
        versionNumVec.push_back(stoi(version));
    }

    int compareVersion(string version1, string version2) {
        vector<int> versionVec1;
        vector<int> versionVec2;
        SplitNumber(versionVec1, version1);
        SplitNumber(versionVec2, version2);
        int minLen = min(versionVec1.size(), versionVec2.size());

        for (int i = 0; i < minLen; ++i){
            if (versionVec1[i] > versionVec2[i]){
                return 1;
            }
            if (versionVec1[i] < versionVec2[i]){
                return -1;
            }
        }

        int maxLen = max(versionVec1.size(), versionVec2.size());
        //version1 長(zhǎng)度大于version2
        if (versionVec1.size() > versionVec2.size()){
            for (int i = minLen; i < maxLen; ++i){
                if (versionVec1[i] != 0){
                    return 1;
                }
            }
        }
        //version2 長(zhǎng)度大于verison1
        if (versionVec2.size() > versionVec1.size()){
            for (int i = minLen; i < maxLen; ++i){
                if (versionVec2[i] != 0){
                    return -1;
                }
            }
        }

        //長(zhǎng)度相等或者長(zhǎng)的版本后綴都為0
        return 0;
    }
};


int main(){
    string version1("1.01.0");
    string version2("1.1");
    Solution solution;
    solution.compareVersion(version1, version2); 
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容