[LeetCode] Compare Version Numbers
The idea is very simple: just extract the numbers from each version number and compare the numbers from beginning to the end. However, C++ seems to have no split
functions like those of Java and Python. So we need to split it by our code. A final note, remember to handle version numbers of different lengths.
The code is as follows.
1 class Solution { 2 public: 3 int compareVersion(string version1, string version2) { 4 vector<int> v1 = version(version1); 5 vector<int> v2 = version(version2); 6 int m = v1.size(), n = v2.size(), i, j; 7 for (i = 0, j = 0; i < m && j < n; i++, j++) 8 if (v1[i] > v2[j]) return 1; 9 else if (v1[i] < v2[j]) return -1; 10 while (i < m && v1[i++]) return 1; 11 while (j < n && v2[j++]) return -1; 12 return 0; 13 } 14 private: 15 vector<int> version(string& version) { 16 int n = version.length(); 17 string vs; 18 vector<int> v; 19 for (int i = 0; i <= n; i++) { 20 if (i == n || version[i] == '.') { 21 v.push_back(stoi(vs)); 22 vs.clear(); 23 if (i == n) break; 24 } 25 else vs += version[i]; 26 } 27 return v; 28 } 29 };
These two lines in the above handle the case of version numbers with different lengths.
1 while (i < m && v1[i++]) return 1; 2 while (j < n && v2[j++]) return -1;
We may also implement version
using some system functions like stringstream
and getline
.
1 class Solution { 2 public: 3 int compareVersion(string version1, string version2) { 4 vector<int> v1 = version(version1); 5 vector<int> v2 = version(version2); 6 int m = v1.size(), n = v2.size(), i, j; 7 for (i = 0, j = 0; i < m && j < n; i++, j++) 8 if (v1[i] > v2[j]) return 1; 9 else if (v1[i] < v2[j]) return -1; 10 while (i < m && v1[i++]) return 1; 11 while (j < n && v2[j++]) return -1; 12 return 0; 13 } 14 private: 15 vector<int> version(string& version) { 16 version += "."; 17 stringstream vs(version); 18 vector<int> v; 19 string t; 20 while (getline(vs, t, '.')) 21 v.push_back(stoi(t)); 22 return v; 23 } 24 };