[InterviewBit] Compare Version Numbers

Compare Version Numbers

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int Solution::compareVersion(string A, string B) {
int i = 0, j = 0;
while(i < A.length() or j < B.length()) {
int ni = i, nj = j;
string AA = "", BB = "";
while(ni < A.length() and A[ni] != '.') AA.push_back(A[ni++]);
while(nj < B.length() and B[nj] != '.') BB.push_back(B[nj++]);
reverse(begin(AA), end(AA));
reverse(begin(BB), end(BB));
while(AA.length() and AA.back() == '0') AA.pop_back();
while(BB.length() and BB.back() == '0') BB.pop_back();
if(AA.length() != BB.length()) return AA.length() > BB.length() ? 1 : -1;
reverse(begin(AA), end(AA));
reverse(begin(BB), end(BB));
if(AA != BB) return AA > BB ? 1 : -1;
i = ni + 1, j = nj + 1;
}
return 0;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/29/PS/interviewbit/compare-version-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.