Title Address: https://oj.leetcode.com/problems/compare-version-numbers/
Title Description:
Compare numbers version1 and version1.
If version1 > version2 return 1, if version1 < version2 return-1, Otherwi SE return 0.
Assume that the version strings is non-empty and contain only digits and the.Character.
The.Character does not represent a decimal point and was used to separate number sequences.
For instance,2.5is not "both and a half" or "half-to-version three", it is the fifth Second-level revision of the second first-level re Vision.
Here are an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
If you see this problem, the AC rate is so low that you try to do it.
Algorithm Ideas: 1. First consider slicing the two strings version1 and Version2, as the test case "1.0.1" may appear, with multiple points.
2. Will follow the "." The split number is placed inside a container vector or in an array.
3. Then compare in turn. It is important to note that there are similar use cases "1.0.0" and "1" are actually equal, so to remove the suffix 0 in the container or array, then there is no concern when comparing.
AC and Test code:
#include <iostream> #include <string> #include <vector>using namespace Std;class solution {Private:ve Ctor<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-Version int compareversion (string version1, String version2) {const char *STR1 = version1.c_s TR (); 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;}
Or to modify the code based on a test case, it is important to consider a more complete test case.
"Leetcode": Compare Version Numbers