题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
经典的字符串分割数字类问题:
class Solution { public: int compare(string version1, string version2) { // write code here int i, j; int v1, v2; for(i = 0, j = 0; i < version1.size() && j < version2.size(); i ++, j ++){ char c1 = version1[i], c2 = version2[j]; if(isdigit(c1)){ int x = 0, k = i; while(k < version1.size() && isdigit(version1[k])) x = x * 10 + version1[k ++] - '0'; v1 = x; i = k - 1; } if(isdigit(c2)){ int x = 0, k = j; while(k < version2.size() && isdigit(version2[k])) x = x * 10 + version2[k ++] - '0'; v2 = x; j = k - 1; } //cout << v1 << " " << v2 << endl; if(v1 > v2) return 1; else if(v1 < v2) return -1; } for(; i < version1.size(); i ++) if(version1[i] != '.' && version1[i] > '0') return 1; for(; j < version2.size(); j ++) if(version2[j] != '.' && version2[j] > '0') return 2; return 0; } };