您的位置:首页 > 其它

[leetcode] 165. Compare Version Numbers 解题报告

2015-12-29 15:55 525 查看
题目链接:https://leetcode.com/problems/compare-version-numbers/

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


思路:一个比较明确的思路是,将字符串以‘.’分割成整数,然后从前往后比较,一旦发现不一样的就说明可以判定大小了。

代码如下:

class Solution {
public:
void divid(string str, vector<int>& vec)
{
string tem;
for(int i = 0; i< str.size(); i++)
{
if(str[i] != '.') tem.append(1, str[i]);
else
{
vec.push_back(stoi(tem));
tem = "";
}
}
}

int compareVersion(string version1, string version2) {
vector<int> nums1, nums2;
version1 += ".", version2 += ".";
divid(version1, nums1);
divid(version2, nums2);
int m =0, n =0;
for(int i = 0; i < max(nums1.size(), nums2.size()); i++)
{
int val1 = 0, val2 = 0;
if(i < nums1.size()) val1 = nums1[i];
if(i < nums2.size()) val2 = nums2[i];
if(val1 > val2) return 1;
if(val1 < val2) return -1;
}
return 0;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: