My solutions in 3 languages


  • 31

    Java, >400ms:

    public class Solution {
        public int compareVersion(String version1, String version2) {
            String[] v1 = version1.split("\\.");
            String[] v2 = version2.split("\\.");
            for (int i = 0; i < Math.max(v1.length, v2.length); i++) {
                int gap = (i < v1.length ? Integer.parseInt(v1[i]) : 0) - (i < v2.length ? Integer.parseInt(v2[i]) : 0);
                if (gap != 0) {
                    return gap > 0 ? 1 : -1;
                }
            }
            return 0;
        }
    }
    

    C++, 4ms:

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            for (; version1 != version2; version1 = nextSubstr(version1), version2 = nextSubstr(version2)) {
                int gap = stoi(version1) - stoi(version2);
                if (gap != 0) {
                    return gap > 0 ? 1 : -1;
                }
            }
            return 0;
        }
        
        string nextSubstr(string str) {
            for (int i = 0; i < str.size(); i++) {
                if (str.at(i) == '.') {
                    return str.substr(i + 1);
                }
            }
            return "0";
        }
    };
    

    Python, around 100ms:

    class Solution:
        # @param a, a string
        # @param b, a string
        # @return a boolean
        def compareVersion(self, version1, version2):
            v1 = version1.split('.')
            v2 = version2.split('.')
            for i in range(max(len(v1), len(v2))):
                gap = (int(v1[i]) if i < len(v1) else 0) - (int(v2[i]) if i < len(v2) else 0)
                if gap != 0:
                    return 1 if gap > 0 else -1
            return 0

  • 0
    C

    Amazing answers with clean code and easy understood thought


  • 0

    Thank you! :)


  • 0

    Thank you for your solution. I have a question about stoi() function. gap = stoi(version1) - stoi(version2);, is the stoi() will automatically extract numbers and ignore the char? For example, is stoi("1.2.3") == 1?


  • 0

Log in to reply
 

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