【leetcode 字串處理】Compare Version Numbers

來源:互聯網
上載者:User

標籤:leetcode   字串處理   

【leetcode 字串處理】Compare Version Numbers

@author:wepon@blog:http://blog.csdn.net/u012162613
1、題目

Compare two version numbers version1 and version1.
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

2、分析題意:題意很清晰,就是比較“版本號碼”大小,給定的版本號碼version1和version2是字串類型的,當version1>version2的時候,返回1,反之返回-1。
這道題屬於細節處理題,除了字串處理繁瑣一點之外沒有什麼。
解題思路:先分別將version1、version2字串按‘.‘分割成多個子串,每個子串轉化成整型存入容器。最後再比較兩個容器中對應位置的數的大小。當然需要考慮它們長度不同的情況。
注意點:(1)version的形式:10.23.1、01.23、1.2.3.4....諸如此類(2)字串轉化成整型,我的程式中直接用庫函數stoi()
3、代碼
class Solution {public:    int compareVersion(string version1, string version2) {        vector<int> result1=getInt(version1);        vector<int> result2=getInt(version2);        int len1=result1.size();        int len2=result2.size();        if(len2<len1) return -1*compareVersion(version2, version1);        int i=0;        while(i<len1 && result1[i]==result2[i]) i++;                if(i==len1){    //str1和str2前len1位都相等,則看看str2後面的len2-len1位是否都為0即可判斷它們的大小            int j=len2-1;            while(j >= len1){                if(result2[j--]!=0) return  -1;            }            return 0;        }else{       //str1和str2前len1位不都相等,直接判斷第i位            if(result1[i]<result2[i]) return -1;            else return 1;        }    }private://將version字串按'.'拆成多個,轉化為整型放入容器    vector<int> getInt(string version){        vector<int> result;        int len=version.size();        int pre=0;        for(int i=0;i<len;i++){            if(version[i]=='.'){                string str(version.begin()+pre,version.begin()+i);  //注意這種初始化形式,左閉右開,即str不包括version[version.begin()+i]                result.push_back(stoi(str));                pre=i+1;            }        }string str(version.begin()+pre,version.end());        result.push_back(stoi(str));        return result;    }};


【leetcode 字串處理】Compare Version Numbers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.