A bit clean c++ code


  • 0
    W
    class Solution {
    public:
        int getSepPos(const string &s) {
            for (unsigned int i = 0; i < s.length(); ++i) {
                if (s[i] == '.') return i;
            }
            return s.length();
        }
        int compareVersion(string version1, string version2) {
            // invalid input
            if (version1.empty() && version2.empty()) return 0;
            
            // revision seperator position
            int spos1 = getSepPos(version1);
            int spos2 = getSepPos(version2);
            
            int fl = 0;
            for (int i = max(spos1, spos2); fl == 0 && i > 0; --i) {
                int x = spos1 - i;
                int y = spos2 - i;
                if (x >= 0) fl += version1[x] - '0';
                if (y >= 0) fl += '0' - version2[y];
            }
            
            if (fl != 0) return fl / abs(fl);
            
            if (spos1 != version1.length()) version1 = version1.substr(spos1+1, version1.length()-1-spos1);
            else version1 = "";
            if (spos2 != version2.length()) version2 = version2.substr(spos2+1, version2.length()-1-spos2);
            else version2 = "";
            
            return compareVersion(version1, version2);
        }
    };
    

    how can do better?


Log in to reply
 

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