题目地址:https://oj.leetcode.com/problems/compare-version-numbers/
题目描述:
Compare two version numbers version1 and version1.
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
看到这道题目的AC率那么低也就尝试着做一做。
算法思路:1.首先考虑将两个字符串version1和version2进行切分,因为可能会出现这样的测试用例"1.0.1",有多个点。
2.将按照"."分割之后的数字放到一个容器vector里面或者一个数组里面就行了。
3.然后依次进行比较。有一点需要注意的是,有类似的用例"1.0.0"和"1"其实是相等的,因此,要将容器或者数组中的后缀0去掉,那么比较的时候就没有什么顾虑了。
AC和测试代码:
#include<iostream> #include<string> #include<vector> using namespace std; class Solution { private: vector<int> v1,v2; public: //split the string by '.' void split_string(const char *str , vector<int> &v) { char *buf = new char[ strlen(str) + 1 ]; strcpy(buf,str); char *p = strtok(buf,"."); while( p!=NULL ) { v.push_back( atoi(p) ) ; p = strtok(NULL,"."); } } //compare two version int compareVersion(string version1, string version2) { const char *str1 = version1.c_str(); const char *str2 = version2.c_str(); split_string(str1,v1); split_string(str2,v2); return judge(); } int judge() { //prune the suffix zero : 1.0 == 1 while( v1.size()!=0 && v1[v1.size()-1]==0 ) { v1.pop_back(); } while( v2.size()!=0 && v2[v2.size()-1]==0 ) { v2.pop_back(); } int size = min( v1.size(),v2.size() ); int i; for(i=0;i<size;i++) { if( v1[i]>v2[i] ) return 1; else if( v1[i]<v2[i] ) return -1; else continue; } if( v1.size() > v2.size() ) { return 1; } else if( v1.size() < v2.size() ) return -1; else return 0; } }; int main() { Solution s ; cout<<s.compareVersion("1.0","1")<<endl; system("pause"); return 0; }
【Leetcode】:Compare Version Numbers
原文地址:http://blog.csdn.net/lavorange/article/details/42048687