版本比较

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:版本后缀为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 长度大于version2
        if (versionVec1.size() > versionVec2.size()){
            for (int i = minLen; i < maxLen; ++i){
                if (versionVec1[i] != 0){
                    return 1;
                }
            }
        }
        //version2 长度大于verison1
        if (versionVec2.size() > versionVec1.size()){
            for (int i = minLen; i < maxLen; ++i){
                if (versionVec2[i] != 0){
                    return -1;
                }
            }
        }

        //长度相等或者长的版本后缀都为0
        return 0;
    }
};


int main(){
    string version1("1.01.0");
    string version2("1.1");
    Solution solution;
    solution.compareVersion(version1, version2); 
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容