https://leetcode.com/problems/compare-version-numbers/description/

 

Compare Version Numbers - LeetCode

Compare Version Numbers - Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at l

leetcode.com

버전2개를 비교하는 문제 

 

풀이

version 2개를 "." 를 기준으로 split하고

길이를 맞춰서 ArrayList에 넣어줬다. 모자른 부분은 0으로 채워둠.

ArrayList 두개 비교 

 
class Solution {
     public int compareVersion(String version1, String version2) {

        // . 을 기준으로 split
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int maxLength = Math.max(v1.length, v2.length);

        // 0 을 채워 size 동일한 ArrayList 만들기
        List<String> arr1 = getArr(v1, maxLength);
        List<String> arr2 = getArr(v2, maxLength);

        // 크기 비교
        for (int i = 0; i < maxLength; i++) {
            if (Integer.parseInt(arr1.get(i)) > Integer.parseInt(arr2.get(i))) return 1;
            else if (Integer.parseInt(arr1.get(i)) < Integer.parseInt(arr2.get(i))) return -1;
        }

	// 버전이 동일하면 0
        return 0;

    }

    ArrayList<String> getArr(String[] str, int maxLength) {
        ArrayList<String> arr = new ArrayList<>(Arrays.asList(str));

        while (arr.size() != maxLength) {
            arr.add("0");
        }
        return arr;
    }
}

 

+ Recent posts