165. Compare Version Numbers (String)

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

注意:版本格式可能会有多个子版本

class Solution {
public:
    int compareVersion(string version1, string version2) {
        vector<int> arr_v1,arr_v2;
        int pos1_pre = 0, pos2_pre = 0, pos1=version1.find_first_of('.'),pos2=version2.find_first_of('.');
        while(pos1!=-1){
            arr_v1.push_back(atoi(version1.substr(pos1_pre,pos1).c_str()));
            pos1_pre = pos1+1;
            pos1 = version1.find_first_of('.',pos1_pre);
        }
        arr_v1.push_back(atoi(version1.substr(pos1_pre).c_str()));
        
        while(pos2!=-1){
            arr_v2.push_back(atoi(version2.substr(pos2_pre,pos2).c_str()));
            pos2_pre = pos2+1;
            pos2 = version2.find_first_of('.',pos2_pre);
        }
        arr_v2.push_back(atoi(version2.substr(pos2_pre).c_str()));
        
        int size1 = arr_v1.size();
        int size2 = arr_v2.size();
        int size = min(size1,size2);
        for(int i = 0; i < size; i++){
            if(arr_v1[i] > arr_v2[i]) return 1;
            else if(arr_v1[i] < arr_v2[i]) return -1;
        }
        if(size == size1){
            for(int i = size; i < size2; i++){
                if(arr_v2[i]!=0) return -1;
            }
            return 0;
        }
        else{
            for(int i = size; i < size1; i++){
                if(arr_v1[i]!=0) return 1;
            }
            return 0;
        }
    }
};

 

posted on 2017-03-22 21:51  joannae  阅读(113)  评论(0编辑  收藏  举报

导航