Skip to content

Latest commit

 

History

History
77 lines (61 loc) · 2.46 KB

165. Compare Version Numbers.md

File metadata and controls

77 lines (61 loc) · 2.46 KB

思路

版本号比较。

思路一

采用双指针的办法从前往后遍历得到每一层的版本子串位置,然后转换成数字再进行比较。

注: string转int可以用函数stoi

思路二

由于这道题我们需要将版本号以'.'分开,那么我们可以借用强大的字符串流stringstream的功能来实现分段和转为整数,使用这种方法写的代码很简洁。

标准库sstream.h定义了三种类型的字符串流:

  • istringstream,由 istream 派生而来,提供读 string 的功能。
  • ostringstream,由 ostream 派生而来,提供写 string 的功能。
  • stringstream,由 iostream 派生而来,提供读写 string 的功能。

这里我们使用istringstream。

学习几个这里需要用到的stringstream的成员函数:

  • good(): 判断是否没有错误;
  • bad(): 与good()相反,判断是否存在错误;
  • eof(): 判断是否到达end-of-file;

注意学习这种将字符串按照某个字符分割开的处理方法!!!

C++

思路一

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int n1 = version1.size(), n2 = version2.size();
        int low1 = 0, low2 = 0, high1, high2;
        while(low1 < n1 || low2 < n2){
            high1 = low1; high2 = low2;
            while(high1 < n1 && version1[high1] != '.') high1++;
            while(high2 < n2 && version2[high2] != '.') high2++;
            
            int num1 = (high1 > n1 ? 0:stoi(version1.substr(low1, high1 - low1)));
            int num2 = (high2 > n2 ? 0:stoi(version2.substr(low2, high2 - low2)));
            if(num1 > num2) return 1;
            else if(num1 < num2) return -1;
            
            low1 = high1 + 1; low2 = high2 + 1;  
        }
        return 0;
    }
};

思路二

class Solution {
public:
    int compareVersion(string version1, string version2) {
        istringstream is1(version1 + '.'), is2(version2 + '.');
        int num1, num2;
        char cdot;
        
        # define OK1 is1.good() // 或者 !is1.fail(), !is1.eof()
        # define OK2 is2.good()
        while(OK1 || OK2){
            num1 = num2 = 0;
            if(OK1) is1 >> num1 >> cdot;
            if(OK2) is2 >> num2 >> cdot;
            
            if(num1 > num2) return 1;
            else if(num1 < num2) return -1;
        } 
        
        return 0;
    }
};