Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions src/week2/괄호회전하기/twalla/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// ✏️ 프로그래머스 괄호 회전하기

// 📶 문제 난이도
// Level 2

// 🔗 문제 링크
// https://school.programmers.co.kr/learn/courses/30/lessons/76502

// ⏱️ 풀이 시간
// 10분

// ✅ 풀이 근거
// 문자열 회전 + stack으로 해결

import java.util.*;

class Solution {

int N;

boolean check(String s) {

Stack<Character> stack = new Stack<>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제가 알기로는 Stack 클래스 자체가 레거시여서 사용하지 않는 걸로 알고 있습니다!

그래서 Dequeue를 이용해서 push, poll 메서드로 Stack을 구현하는 걸로 알고있어용

아마도? synchronized 를 항상해서 성능문제 였던 걸로 기억하는데 한 번 찾아 보시면 좋을 것 같아요!


for (int i = 0; i < N; i++) {

char cur = s.charAt(i);

if (stack.isEmpty() || cur == '[' || cur == '{' || cur == '(') {
stack.push(cur);
continue;
}

if (cur == ']') {
if (stack.peek() == '[') {
stack.pop();
} else {
return false;
}
} else if (cur == '}') {
if (stack.peek() == '{') {
stack.pop();
} else {
return false;
}
} else if (cur == ')') {
if (stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
}

if (!stack.isEmpty()) {
return false;
}

return true;
}

public int solution(String s) {

N = s.length();

int cnt = 0;
for (int i = 0; i < N; i++) {
String moved = s.substring(i, N) + s.substring(0, i);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 Queue 를 이용해서 앞에서 빼고, 뒤에 더하는 방식으로 문제를 풀었었는데

substring 방식도 있겠네요!

약간, 근데 저는 사실 뭔가 새로운 객체를 생성안하고 문제를 풀 수 있지 않을까 생각했는데 떠오르지는 않더라구요.
그래서 다른 방법을 좀 찾아봤는데

  1. string 자체를 2개를 더하는 방법으로 윈도우 슬라이드 느낌으로 검사 하기 -> 이게 진짜 말이 안되는 듯요.
  2. 나머지 연산을 통해 인덱스로 접근하기
    for (int j = 0; j < s.length(); j++) {
          char c = s.charAt((start + j) % s.length());
    }

위의 두 방법이 있어서 약간 구석에 저장해놨다가 써먹어봐요 ㅋㅋ


if (check(moved)) {
cnt += 1;
}
}

return cnt;
}
}
40 changes: 40 additions & 0 deletions src/week2/기지국설치/twalla/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// ✏️ 프로그래머스 괄호 회전하기

// 📶 문제 난이도
// Level 3

// 🔗 문제 링크
// https://school.programmers.co.kr/learn/courses/30/lessons/12979

// ⏱️ 풀이 시간
// 30분

// ✅ 풀이 근거
// 아파트 개수가 최대 20억이기에 O(N)으로는 불가능
//

class Solution {
public int solution(int n, int[] stations, int w) {

int start = 1, current = 1, total = 0, coverage = 2 * w + 1;
for (int i = 0; i < stations.length; i++) {

int station = stations[i];
start = station - w;

if (start > current) {
int gap = start - current;
total += (gap - 1) / coverage + 1;
}

current = Math.max(current, station + w + 1);
}

if (current < n + 1) {
int gap = n + 1 - current;
total += (gap - 1) / coverage + 1;
}

return total;
}
}
45 changes: 45 additions & 0 deletions src/week2/멀리뛰기/twalla/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// ✏️ 프로그래머스 멀리 뛰기

// 📶 문제 난이도
// Level 2

// 🔗 문제 링크
// https://school.programmers.co.kr/learn/courses/30/lessons/12914

// ⏱️ 풀이 시간
// 10분

// ✅ 풀이 근거
// 피보나치로 간단하게 해결

import java.util.*;

class Solution {

long[] cache;
int mod = 1_234_567;

long fibo(int n) {

if (cache[n] != -1) {
return cache[n];
}

if (n == 1) {
return cache[1] = 1;
} else if (n == 2) {
return cache[2] = 2;
}

return cache[n] = (fibo(n - 2) + fibo(n - 1)) % mod;
}

public long solution(int n) {

cache = new long[n + 1];
Arrays.fill(cache, -1);

long answer = fibo(n);
Comment on lines +39 to +42

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

재귀 형식으로 푼 이유가 있을까요?

저는 반복문으로 풀었는데 뭔가 Arrays.fill() 이 내부적으로 최적화 된다고 해도 결국 모든 값을 초기화 해야 하는 것이고, 재귀적으로 하게 되면 새로운 스택?이 쌓이는 거니까 뭔가 이유가 있는 것인지 궁금했습니당

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

피보나치 하면 바로 재귀가 생각났는데, 반복문으로 푸는 방법도 있죠!

return answer;
}
}
87 changes: 87 additions & 0 deletions src/week2/섬연결하기/twalla/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// ✏️ 프로그래머스 섬 연결하기

// 📶 문제 난이도
// Level 3

// 🔗 문제 링크
// https://school.programmers.co.kr/learn/courses/30/lessons/42861

// ⏱️ 풀이 시간
// 20분

// ✅ 풀이 근거
// 모든 노드를 연결하는 최소 비용! 크루스칼로 해결!

import java.util.*;

class Solution {

int N, M;
int[] parent;

void union(int u, int v) {

int fu = find(u);
int fv = find(v);

if (fu != fv) {
parent[fv] = fu;
}
}

int find(int u) {
if (parent[u] == u) {
return u;
}

return parent[u] = find(parent[u]);
}

public int solution(int n, int[][] costs) {

N = n;
M = costs.length;

parent = new int[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
}

PriorityQueue<Node> pq = new PriorityQueue<>();

for (int i = 0; i < M; i++) {
pq.add(new Node(costs[i][0], costs[i][1], costs[i][2]));
}

int answer = 0;
while (!pq.isEmpty()) {

Node cur = pq.poll();

if (find(cur.u) == find(cur.v)) {
continue;
}

union(cur.u, cur.v);
answer += cur.cost;
}
return answer;
}
}

class Node implements Comparable<Node> {
int u;
int v;
int cost;

public Node(int u, int v, int cost) {
this.u = u;
this.v = v;
this.cost = cost;
}

@Override
public int compareTo(Node o) {
return this.cost - o.cost;
}
}
71 changes: 71 additions & 0 deletions src/week2/튜플/twalla/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// ✏️ 프로그래머스 섬 연결하기

// 📶 문제 난이도
// Level 2

// 🔗 문제 링크
// https://school.programmers.co.kr/learn/courses/30/lessons/64065

// ⏱️ 풀이 시간
// 30분

// ✅ 풀이 근거
// 문자열 파싱이 굉장히 귀찮았던 문제

package week2.튜플.twalla;

import java.util.*;

public class Solution {
public int[] solution(String s) {

PriorityQueue<List<Integer>> tuples = new PriorityQueue<>((o1, o2) -> {
return o1.size() - o2.size();
});

int start = 1;
int cnt = 0;
while (start < s.length() - 1) {

if (s.charAt(start) != '{') {
start += 1;
continue;
}

int end = start;
while (s.charAt(end) != '}') {
end += 1;
}

String[] scope = s.substring(start + 1, end).split(",");

Comment on lines +30 to +41

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정규식 파싱 한 번 익혀두면 여러모로 편하더라구요 ㅋㅋ

List<Integer> tuple = new ArrayList<>();
for (String elem : scope) {
tuple.add(Integer.parseInt(elem));
}

tuples.add(tuple);
cnt += 1;

start = end;
}

Set<Integer> set = new HashSet<>();
int[] answer = new int[cnt];

for (int i = 0; i < cnt; i++) {
List<Integer> tuple = tuples.poll();
for (int j = 0; j < tuple.size(); j++) {
int elem = tuple.get(j);
if (set.contains(elem)) {
continue;
}
answer[i] = elem;
set.add(elem);
break;
}
}

return answer;
}
}