Loading

LeetCode 165. 比较版本号

image
image

思路

方法一:直接调用split()和parseInt()库方法

class Solution {
    public int compareVersion(String version1, String version2) {
        /* 调库方法 */
        String[] vs1 = version1.split("\\.");
        String[] vs2 = version2.split("\\.");

        int i = 0;
        while(i < vs1.length || i < vs2.length) {
            int x = 0, y = 0;
            if(i < vs1.length) {
                x = Integer.parseInt(vs1[i]);
            } 

            if(i < vs2.length) {
                y = Integer.parseInt(vs2[i]);
            }

            if (x > y) return 1;
            else if (x < y) return -1;

            i++;
        }

        return 0;
    }
}

方法二:手写split()和parseInt()库方法

class Solution {
    public int compareVersion(String version1, String version2) {
        /* 方法二:手写split与atoi方法 */
        String[] vs1 = splitString(version1, '.');
        String[] vs2 = splitString(version2, '.');

        int i = 0;
        while(i < vs1.length || i < vs2.length) {
            int x = 0, y = 0;
            if(i < vs1.length) {
                x = atoi(vs1[i]);
            } 

            if(i < vs2.length) {
                y = atoi(vs2[i]);
            }

            if (x > y) return 1;
            else if (x < y) return -1;

            i++;
        }

        return 0;
    }

    public String[] splitString(String str, char sp) {
        List<String> list = new ArrayList<>();

        int start = 0;
        for(int i = 0; i < str.length(); ++i) {
            if(str.charAt(i) == sp) {
                list.add(str.substring(start, i));
                start = i+1;
            }
        }

        list.add(str.substring(start, str.length()));

        return list.toArray(new String[]{});
    }

    public int atoi(String num) {
        int r = 1;
        int retVal = 0;
        for(int i = num.length() - 1; i >= 0; i--) {
            int x = num.charAt(i) - '0';
            retVal += x * r;
            r *= 10;
        }
        return retVal;
    }
}
posted @ 2022-05-28 16:12  拾月凄辰  阅读(24)  评论(0编辑  收藏  举报