题目链接: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
思路:五六个月前尝试过,WA到死,搞得我对这题都有心理阴影了。让我想起大一的时候第一次参加ACM小组做poj1001大数运算的时候,各种恶心的测试数据。
会有12.13.19等等可以连续出现版本,所以一个比较明确的思路是,将字符串以‘.’分割成整数,然后从前往后比较,一旦发现不一样的就说明可以判定大小了。
另外还有就是会出现比如10.10.10和10.10.00这种数据。
代码如下:
class Solution { public: void change(vector<int>& vec, string version)//将字符串转为整型 { int i = 0; while(i < version.size()) { stringstream ss; int val; size_t pos = version.find('.', i); string str = version.substr(i, pos-i); ss << str; ss >> val; vec.push_back(val); if(pos == string::npos) return;//防止溢出 i = pos+1; } } int compareVersion(string version1, string version2) { vector<int> vec1; vector<int> vec2; change(vec1, version1); change(vec2, version2); for(int i =0; i < vec1.size() || i < vec2.size(); i++) { int val1 =0, val2=0; if(i < vec1.size()) val1 = vec1[i]; if(i < vec2.size()) val2 = vec2[i]; if(val1 > val2) return 1; else if(val1 < val2) return -1; } return 0; } };