您的位置:首页 > 其它

[Leetcode 165, Easy] Compare Version Numbers

2015-01-25 10:55 495 查看
Problem:

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

Analysis:
The version number is of the pattern, xxx.xxx.xxx.xxx and so on. The right number does not contribute 1 to its left number, if it reaches a certain number. (This dislikes numbers. 19 + 1 will become 20, but not 1 10). Then, the
main idea of the algorithm is convert every sub-string of version number to be a real number. We use a vector to compare two converted version numbers.

Solutions:

C++:

void ConvertStrVerToIntVec(const string& version, vector<int>& intVerVec)
    {
        for(int i = 0; ;) {
            int intVer = 0;
            for(; i < version.size() && version[i] != '.'; ++i) 
                intVer = intVer * 10 + (version[i] - '0');
            if(i == version.size() && intVer == 0)
                break;
            else {
                intVerVec.push_back(intVer);
                if(i == version.size())
                    break; 
                else
                    ++i;
            }
        }
    }

    int compareVersion(string version1, string version2) {
        vector<int> intVerVec1;
        ConvertStrVerToIntVec(version1, intVerVec1);
        if(intVerVec1.size() > 0)
            for(vector<int>::iterator it = intVerVec1.end() - 1; it != intVerVec1.begin();) {
                if(*it == 0)
                    intVerVec1.erase(it--);
                else
                    break;
            }
        
        vector<int> intVerVec2;
        ConvertStrVerToIntVec(version2, intVerVec2);
        if(intVerVec2.size() > 0)
            for(vector<int>::iterator it = intVerVec2.end() - 1; it != intVerVec2.begin();) {
                if(*it == 0)
                    intVerVec2.erase(it--);
                else
                    break;
            }
        
        int i1 = 0;
        int i2 = 0;
        for(; i1 < intVerVec1.size() && i2 < intVerVec2.size(); ++i1, ++i2)
            if(intVerVec1[i1] > intVerVec2[i2])
                return 1;
            else if(intVerVec1[i1] < intVerVec2[i2])
                return -1;
        
        if(i1 < intVerVec1.size() && i2 == intVerVec2.size())
            return 1;
        else if(i1 == intVerVec1.size() && i2 < intVerVec2.size())
            return -1;
        else
            return 0;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: