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;
}
}
'algorithm > leetcode' 카테고리의 다른 글
leetcode 1004. Max Consecutive Ones III (JAVA) (1) | 2023.02.04 |
---|---|
LeetCode 45. Jump Game II (JAVA) (0) | 2023.01.24 |
LeetCode 162. Find Peak Element (JAVA) (0) | 2023.01.24 |
LeetCode 1910. Remove All Occurrences of a Substring (JAVA) (0) | 2023.01.13 |
LeetCode 383. Ransom Note (JAVA) (1) | 2023.01.13 |