2017年4月26日 星期三

[LeetCode] 165. Compare Version Numbers

轉自LeetCode

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings 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 fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
<Solution>
這題主要就是拆解 string 來做比較

首先注意測資有可能是 "1" 和 "1.0.0.1" 這種不等長的情況

想法如下
  • 利用 stringstream 來做切分,每次都讀入一個整數和一個字元。所以在一開始初始化的時候,將原本的字串都多加一個 '.' 字元
  • 不用整個字串都比完,只要有一個位元能比出大小,就回傳答案
code如下(參考資料)

class Solution {
public:
int compareVersion(string version1, string version2) {
stringstream v1(version1 + "."), v2(version2 + ".");
int num_1, num_2;
char dot;
while(v1.good() || v2.good()) {
if(v1.good()) {
v1 >> num_1 >> dot;
}
if(v2.good()) {
v2 >> num_2 >> dot;
}
if(num_1 > num_2) {
return 1;
}
else if(num_1 < num_2) {
return -1;
}
num_1 = num_2 = 0;
}
return 0;
}
};

沒有留言:

張貼留言