leetCode 165. Compare Version Numbers 字符串

发布时间:2020-09-13 07:32:14 作者:313119992
来源:网络 阅读:419

165. Compare Version Numbers

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


思路:

1.将两个版本字符串都分割好存入vector中。

2.比较2个vector中元素的大小。

其中注意:1 == 1.0.0


class Solution {
public:
    vector<int> stringSplit(string s, const char * split)
    {
        vector<int> result;
        const int sLen = s.length();
        char *cs = new char[sLen + 1];
        strcpy(cs, s.data());
        char *p;
        char * end;
        p = strtok(cs, split);
        while (p)
        {
            printf("%s\n", p);
            string tmp(p);
            int v = static_cast<int>(strtol(tmp.c_str(),&end,10));
            result.push_back(v);
            p = strtok(NULL, split);
        }
        return result;
    }
    
    int compareVersion(string version1, string version2) {
        vector<int> vecInt1 = stringSplit(version1,".");
        vector<int> vecInt2 = stringSplit(version2,".");
        
        int i;
        for(i = 0; i < min(vecInt1.size(),vecInt2.size()); i++)
        {
            if(vecInt1[i] < vecInt2[i]) 
                return -1;
            else if(vecInt1[i] > vecInt2[i])
                return 1;
        }
        
        if( vecInt1.size() < vecInt2.size())
        {
            int j = i;
            for(;j <vecInt2.size();j++)
            {
                if(vecInt2[j] > 0)
                    return -1;
            }
            return 0;
        }
        else if(vecInt1.size() > vecInt2.size())
        {
            int j = i;
            for(;j < vecInt1.size();j++)
            {
                if(vecInt1[j] > 0)
                    return 1;
            }
            return 0;
        }
        else
            return 0;

    }
};


推荐阅读:
  1. leetcode--字符串翻转
  2. leetCode 383. Ransom Note 字符串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

字符串 ers tc

上一篇:后端将数据转化为json字符串传输的方法详解

下一篇:Android实现购物车及其他功能的角标

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》