티스토리 뷰
문제출처: https://programmers.co.kr/learn/courses/30/lessons/67257
코딩테스트 연습 - 수식 최대화
IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과 �
programmers.co.kr
풀이법:
1) 주어진 3가지 연산자의 우선순위 순열을 구한다.
2) 구한 순열의 각 우선순위에 따라 식 계산함.
3) 계산하는 방법이 좀 지저분하긴 한데 사람이 연산 순위 지키면서 연산하는 방법이랑 똑같이 햇음
Comment:
1) 순열을 dfs로 구하는 법 배움
2) String으로 주어진 수식 계산하는 코드 짜면서 parsing 경험 좀 더 쌓은 듯
3) ArrayList 그냥 add remove 말고 index로 보통 array 처럼 쓰는게 좀 생소했음
4) postfix로 한 stack에 숫자 연산자 다 때려박고 계산하는 방법도 생각났는데 제대로 기억 안났음 그게 더 좋은 코드일 거 같긴하다
5) 코드가 너무 더럽다
import java.util.ArrayList;
class Solution {
public static ArrayList<Long> operands;
public static ArrayList<String> operators;
public static String exp;
public static long max = -1;
public long solution(String expression) {
operators = new ArrayList();
operands = new ArrayList();
getOp(expression);
exp = String.valueOf(expression);
char[] ops = new char[operators.size()];
for(int i = 0; i < operators.size(); i++) {
ops[i] = operators.get(i).toCharArray()[0];
}
int n = operators.size();
char[] output = new char[n];
boolean[] visited = new boolean[n];
operators = new ArrayList();
makeList(expression);
permutation(ops, output, visited, 0, n, n);
return max;
}
//find operators in expression
public static void getOp(String exp) {
if(exp.contains("*")) {
operators.add("*");
}
if (exp.contains("+")) {
operators.add("+");
}if (exp.contains("-")) {
operators.add("-");
}
}
public static void makeList(String expression) {
char[] exp = expression.toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < exp.length; i++) {
char c = exp[i];
if('0'<= c && c <= '9') {
sb.append(c);
}else {
operands.add(Long.valueOf(sb.toString()));
sb.setLength(0);
operators.add(c+"");
}
}
operands.add(Long.valueOf(sb.toString()));
}
public static void permutation(char[] ops, char[] output, boolean[] visited, int depth, int n, int r) {
if(depth == r) {
System.out.println(output);
calculate(output);
}
for(int i = 0; i < n; i++) {
if(visited[i] != true) {
visited[i] = true;
output[depth] = ops[i];
permutation(ops, output, visited, depth + 1, n, r);
visited[i] = false;
}
}
}
public static void calculate(char[] order) {
ArrayList<Long> toperands = new ArrayList();
ArrayList<String> toperators = new ArrayList();
toperands.addAll(operands);
toperators.addAll(operators);
for(int i = 0; i < order.length; i++) {
String cur = order[i] + ""; //현재 우선순위 연산자
while(toperators.contains(cur)) {
int index = toperators.indexOf(cur);
long temp = calc(toperands.get(index), toperands.get(index + 1), cur);
toperands.remove(index);
toperands.remove(index);
toperands.add(index, temp);
toperators.remove(index);
}
}
long result = Math.abs(toperands.get(0));
System.out.println(result);
if(max < 0) {
max = result;
}else {
if(max < result) {
max = result;
}
}
}
public static long calc(long op1, long op2, String operator) {
long result = 0;
if(operator.equals("+")) {
result = op1 + op2;
}else if(operator.equals("-")) {
result = op1 - op2;
}else if(operator.equals("*")) {
result = op1 * op2;
}
return result;
}
}
'코딩테스트 > 기업코테' 카테고리의 다른 글
[2021 KAKAO INTERN] 숫자 문자열과 영단어 (JAVA) (0) | 2021.09.03 |
---|---|
[2020 KAKAO BLIND] 괄호변환 (JAVA) (0) | 2021.09.02 |
[2021 KAKAO BLIND] 메뉴 리뉴얼 (JAVA) (0) | 2021.08.25 |
[2021 KAKAO BLIND] 신규 아이디 추천 (JAVA) (0) | 2021.08.23 |
[2020 카카오인턴] 키보드 누르기 (0) | 2020.07.11 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 스프링
- decorator
- behavior parameterization
- Java
- 카카오코테
- WORE
- 카카오 인턴
- Java #JIT #JVM
- PatternSyntaxException
- 디자인패턴
- 2020 KAKAO
- nginx 내부
- 카카오 코테
- 2021
- IOC
- Spring
- 모던 자바 인 액션
- WORA
- okhttp3
- 프로그래밍 모델
- jvm
- 코테
- 신규 아이디 추천
- KAKAO 2021
- 카카오
- Kakao Blind
- spring cloud sleuth
- Java #GC #가비지콜렉터 #Garbage Collector
- 2019 Kakao Blind
- zipkin
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함