Input :
Output : [[1], [3,2], [4,5]]
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int x) {
this.val = x;
}
}
public class Q1 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
System.out.println(solve(root));
}
public static List<List<Integer>> solve(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
boolean zigzag = true;
while (!q.isEmpty()) {
int size = q.size();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
if (zigzag) {
list.add(node.val);
} else {
list.add(0, node.val);
}
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
zigzag = !zigzag;
result.add(list);
}
return result;
}
}
주어진 문자열에서 []안에있는 문자를 그 앞에있는 수만큼 반복해서 출력한다.
Input : String s = "12[a]2[bc]2[d]"
Output : "aaaaaaaaaaaabcbcdd"
import java.util.*;
public class Q2 {
public static void main(String[] args) {
String s = "12[a]2[bc]2[d]";
System.out.println(solve(s));
}
public static String solve(String s) {
Stack<Integer> countStack = new Stack<Integer>();
Stack<StringBuilder> stringStack = new Stack<StringBuilder>();
StringBuilder result = new StringBuilder();
// 숫자 담는 변수
int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
k = k * 10 + c - '0';
} else if (c == '[') {
countStack.push(k);
stringStack.push(result);
result = new StringBuilder();
k = 0;
} else if (c == ']') {
StringBuilder sb = stringStack.pop();
for (int i = countStack.pop(); i > 0; i--) {
sb.append(result);
}
result = sb;
} else {
result.append(c);
}
}
return result.toString();
}
}
인프런 강의 : 코딩테스트 전 꼭 알아야 할 개념과 문제(with 자바) - 푸샵맨 코딩스터디