mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 165. Compare Version Numbers.md
This commit is contained in:
parent
a8a41a381a
commit
233047e0df
68
solutions/165. Compare Version Numbers.md
Normal file
68
solutions/165. Compare Version Numbers.md
Normal file
@ -0,0 +1,68 @@
|
||||
# [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。
|
||||
|
||||
**注意学习这种将字符串按照某个字符分割开的处理方法!!!**
|
||||
|
||||
|
||||
# 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++
|
||||
class Solution {
|
||||
public:
|
||||
int compareVersion(string version1, string version2) {
|
||||
istringstream v1(version1 + '.'), v2(version2 + '.');
|
||||
int num1, num2;
|
||||
char dot = '.';
|
||||
while(v1.good() || v2.good()){ // 函数good判断输入流是否good
|
||||
num1 = 0; num2 = 0;
|
||||
if(v1.good()) v1 >> num1 >> dot;
|
||||
if(v2.good()) v2 >> num2 >> dot;
|
||||
|
||||
if(num1 != num2)
|
||||
return num1 > num2 ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user