๐Ÿฅž BE
home

937_Reorder Data In Log Files

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/06/26
ํƒœ๊ทธ
๊ตฌํ˜„
๋ฌธ์ž์—ด
๋‚œ์ด๋„
Medium
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

import java.util.*; class Solution { public String[] reorderLogFiles(String[] logs) { // ๋ฌธ์ž ์ˆซ์ž ๋กœ๊ทธ ๋ฆฌ์ŠคํŠธ List<String> letterLogs = new ArrayList<>(); List<String> digitLogs = new ArrayList<>(); for (String log : logs) { // ์‹๋ณ„์ž ๋ถ„๋ฆฌ ๋กœ์ง // indexOf()๋กœ ์ฒซ๋ฒˆ์งธ ๊ณต๋ฐฑ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜ int space = log.indexOf(" "); String id = log.substring(0, space); String content = log.substring(space +1); // ๋ฌธ์ž ์ˆซ์ž ๋กœ๊ทธ ๋ถ„๋ฆฌ ๋กœ์ง if (Character.isDigit(content.charAt(0))) { digitLogs.add(log); } else { letterLogs.add(log); } } // ๋ฌธ์ž ๋กœ๊ทธ ์ •๋ ฌ Collections.sort(letterLogs, new Comparator<String>() { @Override public int compare(String o1, String o2) { int space1 = o1.indexOf(" "); int space2 = o2.indexOf(" "); String id1 = o1.substring(0, space1); String content1 = o1.substring(space1 + 1); String id2 = o2.substring(0, space2); String content2 = o2.substring(space2 + 1); // compareTo๋กœ ๋น„๊ต. // -> int์˜ ๊ฒฝ์šฐ ํฌ๋‹ค(1), ๊ฐ™๋‹ค(0), ์ž‘๋‹ค(-1) // -> ๋ฌธ์ž์—ด์˜ ๊ฒฝ์šฐ ์•„์Šคํ‚ค๊ฐ’ ๊ธฐ์ค€์œผ๋กœ ๊ณ„์‚ฐ. int comp = content1.compareTo(content2); if (comp == 0) { return id1.compareTo(id2); } return comp; } }); // ๋ฐฐ์—ด์— ์ €์žฅ String[] ans = new String[logs.length]; int i = 0; for (String log : letterLogs) { ans[i++] = log; } for (String log : digitLogs) { ans[i++] = log; } return ans; } }
Java
๋ณต์‚ฌ
split์œผ๋กœ ํ•ด๋ณผ๊นŒ ํ•˜๋‹ค๊ฐ€ ๋ฌธ์ž์—ด ๋ฉ”์„œ๋“œ ์—ฐ์Šต๊ฒธ ์ด๊ฒƒ์ €๊ฒƒ ์จ๋ดค๋Š”๋ฐ ์ฝ”๋“œ๊ฐ€ ์ค„์ค„ ๊ธธ์–ด์ง€๋Š” ๋Š๋‚Œ.
Comparator๋กœ ๋‚ด๋ถ€ ๋น„๊ต์ž๋ฅผ ๋”ฐ๋กœ ํ•˜๋‚˜ํ•˜๋‚˜ ์ปค์Šคํ…€ํ–ˆ์ง€๋งŒ ํ’€์ด ๋ณด๊ณ  ๋‚˜๋‹ˆ ๋ณ„๋กœ ์˜๋ฏธ์—†์–ด ๋ณด์˜€๋‹ค.
์ €๋Ÿด๊ฑฐ๋ฉด ๊ทธ๋ƒฅ ๋ถ„๋ฆฌ ๋กœ์ง์„ ๋ฉ”์„œ๋“œ๋กœ ํ•˜๋‚˜ ๋” ๋งŒ๋“ค์–ด์„œ ํ˜ธ์ถœํ•ด์„œ ์“ฐ๋Š”๊ฒŒ ๋” ๊ฐ„๊ฒฐํ•˜๊ณ  ๊น”๋”ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

๋‹ค๋ฅธ ํ’€์ด (from ์ƒ๊ตฌ๋‹˜ ์ฝ”๋“œ)

public class Ch06_03 { String[] reorderLogFiles(String[] logs) { List<String> letterLogs = new ArrayList<>(); List<String> digitLogs = new ArrayList<>(); for (String log : logs) { if (Character.isLetter(log.split(" ")[1].charAt(0))) { letterLogs.add(log); } else { digitLogs.add(log); } } letterLogs.sort((o1, o2) -> { var s1 = o1.split(" ", 2); var s2 = o2.split(" ", 2); return s1[1].equals(s2[1]) ? s1[0].compareTo(s2[0]) :s1[1].compareTo(s2[1]); }); letterLogs.addAll(digitLogs); return letterLogs.toArray(new String[0]); } }
Java
๋ณต์‚ฌ
split + ๋žŒ๋‹ค๋ฌธ๋ฒ•๊ณผ ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋ฅผ ์จ์„œ ์ฝ”๋“œ๊ฐ€ ๋” ๊น”๋”ํ•ด์กŒ๋‹ค.

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

1. ๋ฌธ์ž ๋กœ๊ทธ ์ˆซ์ž ๋กœ๊ทธ ๋ถ„๋ฆฌ 2. ์‚ฌ์ „์ˆœ, ์‹๋ณ„์ž์ˆœ ๋ฌธ์ž ๋กœ๊ทธ ์ •๋ ฌ ๋ฌธ์ž์—ด ๋ฉ”์„œ๋“œ๋ฅผ ์ ์ ˆํžˆ ํ™œ์šฉํ•˜๋ฉด ํฌ๊ฒŒ ์–ด๋ ต์ง€ ์•Š์€ ๋ฌธ์ œ ๊ฐ™๋‹ค.