Compare Version Numbers

这个其实并不难,只是前期有点恶心,因为可能两边都没小数点,又可能只有一边有小数点,还有可能两边都有,真尼玛麻烦死了。

我的策略很简单,先是根据传入的 string 把它按照小数点用递归的方法分割成若干段,存入容器中,再用迭代的方法比较两个容器就行了。

那么怎么处理有时可能没有小数点的情况呢?

我的解决办法就是将其直接存入容器,然后再存入一个 "0" 这样既没有改变其大小,又使其可以与有小数点的可以比较。

毕竟这一次是我纯粹自己想出来的,以下是代码:

vector<string> splitStringByDot(string& str)
{
    vector<string> splitedData;
    
    function<void(string)> split;
    split = [&](string s)
    {
        auto dotIndex = s.find(".");
        
        if (dotIndex == string::npos) {
            splitedData.push_back(s);
            splitedData.push_back("0");
            return;
        }
        
        splitedData.push_back(string(str.cbegin(), str.cbegin() + dotIndex));
        str.erase(str.cbegin(), str.cbegin() + dotIndex + 1);
        split(str);
    };
    split(str);
    return splitedData;
}

int compareSegments(vector<string>& segment1, vector<string>& segment2)
{
    auto begin1 = segment1.cbegin();
    auto begin2 = segment2.cbegin();
    
    auto strToInt = [](const string& s){return atoi(s.data());};
    
    while (begin1 != segment1.cend() && begin2 != segment2.cend()) {
        if (strToInt(*begin1) < strToInt(*begin2)) {
            return -1;
        }
        
        if (strToInt(*begin1) > strToInt(*begin2)) {
            return 1;
        }
        
        ++begin1;
        ++begin2;
    }
    return 0;
}

int compareVersion(string version1, string version2)
{
    auto versionSegments1 = splitStringByDot(version1);
    auto versionSegments2 = splitStringByDot(version2);
    
    return compareSegments(versionSegments1, versionSegments2);
}
原文地址:https://www.cnblogs.com/wuOverflow/p/4688812.html