My C++ solution, scanning


  • 0
    X
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int n1 = version1.length(), n2 = version2.length();
            int p1 = 0, p2 = 0;
            int start1 = 0, start2 = 0;
            while (p1 < n1 || p2 < n2) {
                p1 = start1;
                p2 = start2;
                while (p1 < n1 && version1[p1] != '.') p1++;
                while (p2 < n2 && version2[p2] != '.') p2++;
                int v1 = 0;
                if (p1 > start1)
                    v1 = stoi( version1.substr(start1, p1 - start1) );
                int v2 = 0;
                if (p2 > start2)
                    v2 = stoi( version2.substr(start2, p2 - start2) );
                if (v1 > v2) return 1;
                if (v1 < v2) return -1;
                if (p1 < n1)
                    start1 = p1 + 1;
                else
                    start1 = p1;
                if (p2 < n2)
                    start2 = p2 + 1;
                else
                    start2 = p2;
            }
            return 0;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.