Accepted Java solution


  • 0
    F

    straightforward comparing of each number between "." when one of the string is exhausted we treat the remaining as 0

    public int compareVersion(String v1, String v2) {
    		if (v1 == null && v2 == null) {
    			return 0;
    		} else if (v1.isEmpty() && v2.isEmpty()) {
    			return 0;
    		} else if (v1 == null || v1.isEmpty()) {
    			return -1;
    		} else if (v2 == null || v2.isEmpty()) {
    			return 1;
    		}
    		int te1 = -1;
    		int te2 = -1;
    		while (true) {
    			int ts1 = te1 + 1;
    			int ts2 = te2 + 1;
    			String num1 = "0";
    			String num2 = "0";
    			if (ts1 == v1.length() + 1 && ts2 == v2.length() + 1) {
    				// must stop when equal to +1
    				return 0;
    			} 
    			// if one of them is done, treat as 0
    			te1 = v1.indexOf(".", ts1);
    			// must have start
    			te2 = v2.indexOf(".", ts2);
    			if (te1 == -1) {
    				te1 = v1.length();
    			}
    			if (te2 == -1) {
    				te2 = v2.length();
    			}
    			if (ts1 < te1) {
    				num1 = v1.substring(ts1, te1);
    			}
    			if (ts2 < te2) {
    				num2 = v2.substring(ts2, te2);
    			}
    			Integer i1 = Integer.valueOf(num1);
    			Integer i2 = Integer.valueOf(num2);
    			if (i1 < i2) {
    				return -1;
    			} else if (i1 > i2) {
    				return 1;
    			}
    
    		}
    
    	}

  • 0
    R

    Integer can cause overflow issue. I would suggest to compare string itself.


Log in to reply
 

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