[165]Compare Version Numbers

来源:互联网 发布:程序员专用昵称 编辑:程序博客网 时间:2024/06/05 08:19

【题目描述】

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

【思路】

将version1和version2以.为分隔符分成若干个字符串,然后再逐个比较。

要注意的是atoi函数的类型要求是char*,stoi函数才能将字符串转换成整型数。

【代码】

class Solution {public:    int compareVersion(string version1, string version2) {        int ans;        vector<string> v1,v2;        int len1=version1.length();        int len2=version2.length();        string s="";        for(int i=0;i<len1;i++){            if(version1[i]=='.'){                v1.push_back(s);                s="";                continue;            }            s=s+version1[i];        }        v1.push_back(s);        s="";        for(int i=0;i<len2;i++){            if(version2[i]=='.'){                v2.push_back(s);                s="";                continue;            }            s=s+version2[i];        }        v2.push_back(s);        len1=v1.size();        len2=v2.size();        for(int i=0;i<min(len1,len2);i++){            int n1=stoi(v1[i]);            int n2=stoi(v2[i]);            if(n1<n2) return -1;            if(n1>n2) return 1;        }        if(len1<len2){            for(int j=len1;j<len2;j++){                if(stoi(v2[j])!=0) return -1;            }            return 0;        }        else if(len1>len2){            for(int j=len2;j<len1;j++){                if(stoi(v1[j])!=0) return 1;            }            return 0;        }        else return 0;    }};


0 0