165. Compare Version Numbers

来源:互联网 发布:数据结构与算法 英文 编辑:程序博客网 时间:2024/06/04 18:48

题目

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
分析

根据.划分各段分量,转换成数字形式比较即可,注意各种特殊情况,如01.1=1.1;1.0002=1.2;1.0.0.000=1=1.0.0;1.2<1.10;1.2<1.2.3

class Solution {public:    int compareVersion(string version1, string version2) {        int start1=0,end1=0,start2=0,end2=0;        while(end1<version1.size()&&end2<version2.size())        {            while(end1<version1.size()&&version1[end1]!='.')//确定两个.之间的起点和终点            {                end1++;            }            while(end2<version2.size()&&version2[end2]!='.')            {                end2++;            }                       string s1=version1.substr(start1,end1-start1);//截取两个.之间的字符串            string s2=version2.substr(start2,end2-start2);            int version_1=atoi(s1.c_str());//将其转换成数字形式,因此不用管x.0123形式排在首位的0,转换过程中会自动抹去            int version_2=atoi(s2.c_str());            if(version_1==version_2)//比较版本号大小,如果相等则移动各区间标识,进行下一轮比较            {                end1++;                start1=end1;                end2++;                start2=end2;            }            else            {                if(version_1<version_2)                    return -1;                else                    return 1;                            }        }        /*可能出现x.x.0.0和x.x或者x.x.0.000.0和x.x.0.0.0.0或者x.x.0.1和x.x的情况,此时有一个遍历到头,一个还没有,因此这两个循环过滤掉多余的0和.*/        while(end1<version1.size()&&(version1[end1]=='0'||version1[end1]=='.'))        {            end1++;        }        while(end2<version2.size()&&(version2[end2]=='0'||version2[end2]=='.'))        {            end2++;        }        if(end1>version1.size()-1&&end2>version2.size()-1)//当两个尾区间都超过版本号尺寸时,证明在前面的比较中各分量都相等        {            return 0;        }        else        {            if(end1>version1.size()-1)//否则谁还有剩余字段谁就是大的版本号,比如1.2.1>1.2            {                return -1;            }            else                return 1;        }    }};


0 0
原创粉丝点击