165. 比较版本号

package leetcode;

public class demo_165 {
    public int compareVersion(String version1, String version2) {
        String[] v1=version1.split("\\.");
        String[] v2=version2.split("\\.");
        int i=0;
        for(;i<v1.length&&i<v2.length;i++) {
            v1[i]=cancelzero(v1[i]);
            v2[i]=cancelzero(v2[i]);
            if(Integer.valueOf(v1[i])>Integer.valueOf(v2[i])) {
                return 1;
            }
            if(Integer.valueOf(v1[i])<Integer.valueOf(v2[i])) {
                return -1;
            }
        }
        if(i==v1.length&&i!=v2.length) {
            for(;i<v2.length;i++) {
                v2[i]=cancelzero(v2[i]);
                if(!v2[i].equals("0")) {return -1;}
            }
        }
        if(i!=v1.length&&i==v2.length) {
            for(;i<v1.length;i++) {
                v1[i]=cancelzero(v1[i]);
                if(!v1[i].equals("0")) {return 1;}
            }
        }
        return 0;
    }
    public String cancelzero(String s) {
        s=s.replaceFirst("0*", "");
        if(s.equals("")) {return "0";}
        else {
            return s;
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        demo_165 d165=new demo_165();
        String version1="1.0.1";
        String version2="1";
        System.out.println(d165.compareVersion(version1, version2));
    }

}

 

上一篇:Go语言分金币题


下一篇:1133 Splitting A Linked List