Compare Version Numbers

题目来源
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

这道题目呢,一开始题目理解错了以为是只能有一个点,然后错了,是可以有多个点的,比如说1.1.2.2这样子。想法很简单,我想的是用递归的方法,把字符串转换成数字,依次比较每个小点之前的版本号,一样的继续往下比,代码如下:

class Solution {
public:
    int compareVersion(string version1, string version2) {
        return compare(version1, version2);
    }
    
    int compare(string v1, string v2)
    {
        int p1 = v1.find_first_of('.');
        int p2 = v2.find_first_of('.');
        int z1, z2;
        if (p1 == -1)
            z1 = convert2num(v1);
        else
            z1 = convert2num(v1.substr(0, p1));
        if (p2 == -1)
            z2 = convert2num(v2);
        else
            z2 = convert2num(v2.substr(0, p2));
        if (z1 > z2)
            return 1;
        else if (z1 < z2)
            return -1;
        else {
            if (p1 == -1 && p2 == -1)
                return 0;
            return compare(p1 == -1 ? "0" : v1.substr(p1+1), p2 == -1 ? "0" : v2.substr(p2+1));
        }
    }
    
    int convert2num(string s)
    {
        int n = s.length();
        int r = 0;
        for (int i=0; i<n; i++) {
            r = r * 10 + (s[i] - '0');
        }
        return r;
    }
};

看看别人的,是简洁了一些。

class Solution {
public:
    int compareVersion(string version1, string version2) {
    int i = 0; 
    int j = 0;
    int n1 = version1.size(); 
    int n2 = version2.size();
    
    int num1 = 0;
    int num2 = 0;
    while(i<n1 || j<n2)
    {
        while(i<n1 && version1[i]!='.'){
            num1 = num1*10+(version1[i]-'0');
            i++;
        }
        
        while(j<n2 && version2[j]!='.'){
            num2 = num2*10+(version2[j]-'0');;
            j++;
        }
        if(num1>num2) return 1;
        else if(num1 < num2) return -1;
        num1 = 0;
        num2 = 0;
        i++;
        j++;
    }
        return 0;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容