【leetcode文字列処理】Compre Version Numbers


【leetcode文字列処理】Compre Version Numbers
@author:wepon
@ブログ:http://blog.csdn.net/u012162613
1、テーマ
Compre two version numbers version 1 and version 1.If version 1 > version 2 return 1,if version 1 < version 2 return-1,otherswise return 0.
You may asome that the version stings 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 fift second-level revision of the second first-level revision.
Here is an example of version numbers ordeng:
0.1 < 1.1 < 1.2 < 13.37
2、分析
題名がはっきりしています。バージョン番号を比較し、与えられたバージョン番号version 1とversion 2は文字列タイプで、version 1>version 2の場合は1を返し、逆に-1を返します。
この問題は細部の処理問題です。文字列の処理が煩雑な点を除いては何もありません。
問題解決の考え方:まず、version 1、version 2の文字列を'.'に分割し、複数のサブストリングに分割し、各サブストリングを形に変えてコンテナに預け入れます。最後に、二つの容器の中の対応する位置の数の大きさを比較します。もちろん、それらの長さが異なる場合を考慮する必要があります。
注意点:
(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;
    }
};