Sharing a Concise Java Solution


  • 1
    M

    Here's my accepted Java solution. Basically it iterates over every number between dots if the two numbers are always matching. Using dot index to indicate the location of the dot within version 1 or 2, and be a little careful with parsing the correct string and updating it for future iterations.

    public int compareVersion(String version1, String version2) {
        int result = 0, dot1 = 0, dot2 = 0, v1, v2;
        
        while (result == 0 && (dot1 >= 0 || dot2 >= 0)) {
            dot1 = version1.indexOf('.');
            dot2 = version2.indexOf('.');
            if (dot1 < 0) {
                v1 = Integer.parseInt(version1);
                if (v1 != 0) version1 = "0";
            } else {
                v1 = Integer.parseInt(version1.substring(0, dot1));
                version1 = version1.substring(dot1 + 1);
            }
            if (dot2 < 0) {
                v2 = Integer.parseInt(version2);
                if (v2 != 0) version2 = "0";
            } else {
                v2 = Integer.parseInt(version2.substring(0, dot2));
                version2 = version2.substring(dot2 + 1);
            }
            result = compareNumber(v1, v2);
        }
        
        return result;
    }
    
    private int compareNumber(int v1, int v2) {
        if (v1 == v2) {
            return 0;
        } else {
            return v1 < v2 ? -1 : 1;
        }
    }

  • 0
    L

    Mine is similar idea:

    public class Solution {
        public int compareVersion(String version1, String version2)
        {
            for (int pos1 = 0, pos2 = 0; pos1 < version1.length() || pos2 < version2.length(); )
            {
                final int start1;
                for (start1 = pos1; pos1 < version1.length() && '.' != version1.charAt(pos1); ++pos1)
                {
                    
                }
                
                final int val1 = (start1 != pos1) ? Integer.valueOf(version1.substring(start1, pos1++)) : 0;
                
                final int start2;
                for (start2 = pos2; pos2 < version2.length() && '.' != version2.charAt(pos2); ++pos2)
                {
                    
                }
                
                final int val2 = (start2 != pos2) ? Integer.valueOf(version2.substring(start2, pos2++)) : 0;
    
                if (val1 != val2)
                {
                    return (val1 < val2) ? -1 : 1;
                }
            }
            
            return 0;
        }
    }

  • 0
    R

Log in to reply
 

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