LeetCode/solutions/165. Compare Version Numbers.md

78 lines
2.5 KiB
Markdown
Raw Normal View History

2019-08-29 09:19:25 +00:00
# [165. Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/)
# 思路
版本号比较。
## 思路一
采用双指针的办法从前往后遍历得到每一层的版本子串位置,然后转换成数字再进行比较。
> 注: string转int可以用函数`stoi`。
## 思路二
由于这道题我们需要将版本号以'.'分开那么我们可以借用强大的字符串流stringstream的功能来实现分段和转为整数使用这种方法写的代码很简洁。
标准库sstream.h定义了三种类型的字符串流
* istringstream由 istream 派生而来,提供读 string 的功能。
* ostringstream由 ostream 派生而来,提供写 string 的功能。
* stringstream由 iostream 派生而来,提供读写 string 的功能。
这里我们使用istringstream。
2020-07-01 00:48:42 +00:00
学习几个这里需要用到的stringstream的成员函数:
* `good()`: 判断是否没有错误;
* `bad()`: 与`good()`相反,判断是否存在错误;
* `eof()`: 判断是否到达end-of-file
2019-08-29 09:19:25 +00:00
**注意学习这种将字符串按照某个字符分割开的处理方法!!!**
# C++
## 思路一
``` 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;
}
};
```
## 思路二
``` C++
2020-07-01 00:48:42 +00:00
class Solution {
2019-08-29 09:19:25 +00:00
public:
int compareVersion(string version1, string version2) {
2020-07-01 00:48:42 +00:00
istringstream is1(version1 + '.'), is2(version2 + '.');
2019-08-29 09:19:25 +00:00
int num1, num2;
2020-07-01 00:48:42 +00:00
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;
2019-08-29 09:19:25 +00:00
2020-07-01 00:48:42 +00:00
if(num1 > num2) return 1;
else if(num1 < num2) return -1;
}
2019-08-29 09:19:25 +00:00
return 0;
}
};
```