• [LeetCode] Compare Version Numbers


    The idea is very simple: just extract the numbers from each version number and compare the numbers from beginning to the end. However, C++ seems to have no split functions like those of Java and Python. So we need to split it by our code. A final note, remember to handle version numbers of different lengths.

    The code is as follows.

     1 class Solution {
     2 public:
     3     int compareVersion(string version1, string version2) {
     4         vector<int> v1 = version(version1);
     5         vector<int> v2 = version(version2);
     6         int m = v1.size(), n = v2.size(), i, j;
     7         for (i = 0, j = 0; i < m && j < n; i++, j++)
     8             if (v1[i] > v2[j]) return 1;
     9             else if (v1[i] < v2[j]) return -1;
    10         while (i < m && v1[i++]) return 1;
    11         while (j < n && v2[j++]) return -1;
    12         return 0;
    13     }
    14 private:
    15     vector<int> version(string& version) {
    16         int n = version.length();
    17         string vs;
    18         vector<int> v;
    19         for (int i = 0; i <= n; i++) {
    20             if (i == n || version[i] == '.') { 
    21                 v.push_back(stoi(vs));
    22                 vs.clear();
    23                 if (i == n) break;
    24             }
    25             else vs += version[i];
    26         }
    27         return v;
    28     }
    29 };

    These two lines in the above handle the case of version numbers with different lengths.

    1 while (i < m && v1[i++]) return 1;
    2 while (j < n && v2[j++]) return -1; 

    We may also implement version using some system functions like stringstream and getline.

     1 class Solution {
     2 public:
     3     int compareVersion(string version1, string version2) {
     4         vector<int> v1 = version(version1);
     5         vector<int> v2 = version(version2);
     6         int m = v1.size(), n = v2.size(), i, j;
     7         for (i = 0, j = 0; i < m && j < n; i++, j++)
     8             if (v1[i] > v2[j]) return 1;
     9             else if (v1[i] < v2[j]) return -1;
    10         while (i < m && v1[i++]) return 1;
    11         while (j < n && v2[j++]) return -1;
    12         return 0;
    13     }
    14 private:
    15     vector<int> version(string& version) {
    16         version += "."; 
    17         stringstream vs(version);
    18         vector<int> v;
    19         string t;
    20         while (getline(vs, t, '.'))
    21             v.push_back(stoi(t));
    22         return v;
    23     }
    24 };
    
    
  • 相关阅读:
    matplotlib 画图
    Mac anzhuangxgboost
    scala _ parameter
    cv 验证
    groupie
    pandas map, apply, applymap区别
    画图
    xgboost dmatrix中的 weight的重要性
    自然语言处理的训练范式
    java-处理大容量文本文件,行内分格符为TAB的方法
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4740846.html
Copyright © 2020-2023  润新知