LeetCode:Compare Version Numbers

来源:互联网 发布:准提法网络佛学院官网 编辑:程序博客网 时间:2024/09/21 06:19

这道题的难度是Easy,但是通过率不高,主要是题目给的不是很明确,测试的场景也比较复杂。

经过多番调试,终于Accepted。目前的解决方式采用了递归。采用非递归的方式,需要记录连续两个'.'的位置,觉得操作太烦了,故没有使用。

int compareVersion(string version1, string version2)

    {

        intpos1 = version1.find_first_of('.');

        intpos2 = version2.find_first_of('.');

        intm,n;

        if(pos1!=-1)

        {

            m= atoi(version1.substr(0,pos1).c_str());

        }

        else

        {

            m=atoi(version1.c_str());

        }

        if(pos2!=-1)

        {

            n= atoi(version2.substr(0,pos2).c_str());

        }

        else

        {

            n= atoi(version2.c_str());

        }

        if(m==n)

        {

            if(pos1!=-1&&pos2!=-1)

            {

                returncompareVersion(version1.substr(pos1+1),version2.substr(pos2+1));

            }

            elseif(pos1!=-1)

            {

                returncompareVersion(version1.substr(pos1+1),"0");    

            }

            elseif (pos2!=-1)

            {

                returncompareVersion("0",version2.substr(pos2+1));    

            }

            else

            {

                return0;

            }

        }

        returnm<<spanstyle="color:navy">n?-1:1;

    }

0 0