题目名称
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
分析
题目中并没有说明版本号只有1.1,1.2这种类型,还有1.2.3,1.2.3.4等都是版本号。而且在比较的过程中,1.1也可以和1.1.2比较。
一个简单的方法就是将两个字符串按照“.”分割后分别存储到两个vector中,如果vector的大小不一样,则对小的进行扩充,使两个vector大小相等,然后遍历两个vector,进行比较。
C++代码
class Solution {
public:
vector<int> convert(string& s){
stringstream ss;
vector<int> res;
s+=".";
int j;
int size=s.size();
for(int i=0;i<size;i++){
//这一步非常重要,防止ss复用
ss.clear();
//寻找i之后第一次出现“.”的位置
j = s.find(".",i);
string sub = s.substr(i,j-i);
//清空缓冲区
ss.str("");
ss.str(sub);
int num;
ss >> num;
res.push_back(num);
i=j;
}
return res;
}
int compareVersion(string version1, string version2) {
vector<int> v1 = convert(version1);
vector<int> v2 = convert(version2);
int maxSize = (v1.size()>v2.size())?v1.size():v2.size();
v1.resize(maxSize);
v2.resize(maxSize);
for(int i=0;i<maxSize;i++){
if(v1[i]>v2[i])
return 1;
else if(v1[i]<v2[i])
return -1;
}
return 0;
}
};
总结
C++中涉及到数据类型转换时,用stringstream最方便了。在解决这道题时,因为一开始没有对字符串流进行clear()操作,导致了第一次出现的值一直被复用,从这道题中我也学到了很多,之后我会写一篇用stringstream进行数据转换的文章。