[java/3ms] Using split and parseInt. This problem wastes us time by....


  • 1

    This problem wastes us time by not clarifying the behavior such as leading 0, like "01.000001" or trailing 0, like "1.0" == "1". Kidding me? The whole algor I used at first was discarded due to this unclarified stuff.

    If your time is being wasted, give me high five!!!!!!!

    Well, I think java's string literal can't compare with those of python, ruby even its old rival cpp. To escape . in a regex, u need to use "\\.". While in python or ruby, '\.' is enough.

    public int compareVersion(String version1, String version2) {
            String[] v1 = version1.split("\\.");
            String[] v2 = version2.split("\\.");
            
            int i = 0;
            for (int min = Math.min(v1.length, v2.length); i < min; i++) {
                int v1i = Integer.parseInt(v1[i]);
                int v2i = Integer.parseInt(v2[i]);
                if (v1i > v2i) {
                    return 1;
                } else if (v1i < v2i) {
                    return -1;
                }
            }
    
            if (v1.length == i) {
                while (i < v2.length) {
                    if (Integer.parseInt(v2[i++]) > 0)
                        return -1;
                }
            } else {
                while (i < v1.length) {
                    if (Integer.parseInt(v1[i++]) > 0)
                        return 1;
                }
            }
            
            return 0;
        }
    

  • 0

    leading 0 is really annoying and unclear here.


  • 0

    @mr-vincent yeah, they didn't clarify it. XD


Log in to reply
 

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