LeetCode 165: 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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


分析,题目要求比较Version Number,按题目给出的示例,将Version分为Main Version和Sub Version,如"0.1" Main version为0, SubVersion为1。很容易根据 ” “将字符串”0.1“分为 Main和Sub两个部分。得到如下的代码:

class Solution {
public:
   	int getMainVersion(string version){
		int index = version.find(".");
		string substr;
		if (index == -1)
		{
			substr = version;
		}
		substr = version.substr(0, index);
		return atoi(substr.c_str());
	}
	int getSubVersion(string version){
		int index = version.find(".");
		string substr;
		if (index == -1)
		{
			return 0;
		}
		substr = version.substr(index+1, version.size()-index);
		return atoi(substr.c_str());
	}
       int compareVersion(string version1, string version2){
		int mainVersion1 =getMainVersion(version1);
		
		int mainVersion2 = getMainVersion(version2);
		
		if (mainVersion1 != mainVersion2)
		{
			return (mainVersion1 > mainVersion2) ? 1: -1;
		}
		int subVersion1 = getSubVersion(version1);
		int subVersion2 = getSubVersion(version2);
		if (subVersion1 != subVersion2)
		{
			return (subVersion1 > subVersion2) ? 1: -1;
		}
		return 0;
	}
};

很不幸,提交失败,题目的测试用例并不是只有主、从版本号。还有”10.6.5“这样的3段版本号。

所以需要设置一个数组,用于保存版本号各段信息,分离版本号的方法有点类似于Java中的Split方法。

得到要比较的两个版本字符串对应的版本号数组后,将两个版本号数组通过添加0对齐,然后再按位比较。

代码如下:

class Solution {
public:
    //通过.号分隔字符串得到版本号数组,如”0.1.2“ 对应<0,1,2>
	vector<int> getVersion(string version){
		vector<int> result;
		if (version.size()<= 0)
			return result;
		int lastPos = 0, index;
		while ((index = version.find(".", lastPos)) != -1)
		{
			if (lastPos == index)
			{
				result.push_back(0);
			}else{
				string substr = version.substr(lastPos, index-lastPos);
				result.push_back(atoi(substr.c_str()));
			}
			lastPos =  index + 1;
		}
		string lastStr = version.substr(lastPos);
		result.push_back(atoi(lastStr.c_str()));
		return result;
	}
	
	int compareVersion(string version1, string version2){
		vector<int> v1 = getVersion(version1);
		vector<int> v2 = getVersion(version2);
		//将两版本号数组通过加0长度对齐
		int length = v1.size() - v2.size();
		for (int i=0; i<abs(length); i++)
		{
			if (length>0)
				v2.push_back(0);
			else
				v1.push_back(0);
		}
		
		//逐位比较数组元素
		for (int index = 0; index<v1.size(); index++)
		{
			if(v1[index] != v2[index])
				return (v1[index]>v2[index]) ? 1: -1;
		}
	
		return 0;
	}
};






你可能感兴趣的:(LeetCode,version,compare,numb,版本号比较)