LeetCode:Compare Version Numbers

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

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

int compareVersion(string version1, string version2)

    {

        int pos1 = version1.find_first_of('.');

        int pos2 = version2.find_first_of('.');

        int m,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)

            {

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

            }

            else if(pos1!=-1)

            {

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

            }

            else if (pos2!=-1)

            {

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

            }

            else

            {

                return 0;

            }

        }

        return m<<span style="color:navy">n?-1:1;

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值