들어가며
배운점
1.조건에 맞게 커스텀 Comparator를 구현하는 것
2. List -> Array로 변형하기
3. List concat 하는 두 가지 방법(Stream.concat , List.addAll())
문제
난이도: medium
링크 : https://leetcode.com/problems/reorder-data-in-log-files/description/
Reorder Data in Log Files - LeetCode
Can you solve this real interview question? Reorder Data in Log Files - You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. There are two types of logs: * Letter-logs: All words (except the
leetcode.com
조건에 맞게 정렬 하는 문제 였다.
커스텀 comparator를 이용하면 다양한 조건으로 비교조건을 만들 수 있어서 좋았다.
풀이
🌊아이디어
1. 커스텀 정렬 조건 만들기
🌊코드
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class _Sort937 {
public String[] reorderLogFiles(String[] logs) {
List<String> digits = new ArrayList<>();
List<String> letters = new ArrayList<>();
for (String log : logs) {
isdigit(log, digits,letters);
}
return Stream.concat(
letters.stream()
.sorted((s1, s2) -> {
String[] split1 = s1.split(" ");
String[] split2 = s2.split(" ");
int result = s1.substring(s1.indexOf(" ") + 1).compareTo(
s2.substring(s2.indexOf(" ") + 1)
);
// If the second word comparison is equal, compare by the first word
if (result == 0) {
result = split1[0].compareTo(split2[0]);
}
return result;
}), digits.stream()
).toArray(String[]::new);
}
public void isdigit(String data,List<String> digits,List<String> letters) {
String subData = data.substring(data.indexOf(" ") + 1);
if(subData.matches(".*\\d+.*"))
digits.add(data);
else letters.add(data);
}
}728x90
'알고리즘 기본 > 구현' 카테고리의 다른 글
| [leetcode] leetcode 49 애너그룹 만들기 (그루핑) (1) | 2023.12.25 |
|---|---|
| [Leet Code] leetcode 819 java 구현 (0) | 2023.12.25 |