function solution(expression) {
var answer = 0;
const tokens = []
const operator = new Set()
let num = ''
for(let i=0; i<expression.length; i++){
const char = expression[i];
if(char < 10 || char >= 0){
num+=char;
}else{
operator.add(char);
tokens.push(+num);
tokens.push(char);
num = '';
}
}
tokens.push(+num);
const calc = (sign, a, b) => {
if(sign==='*'){
return a * b;
}else if(sign==='-'){
return a - b;
}else{
return a + b;
}
}
const getAns = (tokens, priority) => {
let ans = [...tokens]
priority.forEach(sign => {
if(!operator.has(sign)){
return;
}
const stack=[]
for(let i=0; i<ans.length; i++){
const token = ans[i];
if(token === sign){
const prev = stack.pop();
stack.push(calc(sign, prev, ans[i+1]));
i++;
}else{
stack.push(token);
}
}
ans = stack;
})
return Math.abs(ans[0]);
}
const findPermutations = (str) => {
if(str.length===1){
return str;
}
const permutations = [];
for(let i=0; i<str.length; i++){
const char = str[i];
const remains = str.slice(0, i) + str.slice(i+1,str.length);
for(let permutation of findPermutations(remains)){
permutations.push((char + permutation));
}
}
return permutations;
}
const priorities = findPermutations('*-+').map(p => p.split(''))
return Math.max(...priorities.map(p => getAns(tokens, p)));
}
Level
프로그래머스 Lv2
Day
13일
kakao
2020 카카오 인턴십