const strToArr = (str) => {
const arrOfStr = str.split("").slice(1, str.length - 1);
const limit = arrOfStr.length;
const convertedArr = [];
const stack = [];
let temp = [];
let num = "";
for (let i = 0; i < limit; i++) {
const char = arrOfStr[i];
if (char == "{") {
stack.push(0);
continue;
}
if (char == ",") {
if (arrOfStr[i - 1] == "}") {
continue;
} else {
temp.push(parseInt(num));
num = "";
continue;
}
}
if (char == "}") {
temp.push(parseInt(num));
num = "";
stack.pop();
convertedArr.push(temp);
temp = [];
continue;
}
num += char;
}
return convertedArr;
};
const sortHelper1 = (a, b) => {
if (a.length > b.length) {
return 1;
}
return -1;
};
const sortHelper2 = (a, b) => {
if (a[1] > b[1]) {
return 1;
}
return -1;
};
const reduceHelper = (acc, current, idx, origin) => {
current.forEach((num) => {
if (!acc.hasOwnProperty(num)) {
acc[num] = idx;
}
});
if (idx == origin.length - 1) {
return Object.entries(acc)
.sort(sortHelper2)
.map(([num, idx]) => parseInt(num));
}
return acc;
};
const solution = (s) => {
const convertedArr = strToArr(s);
return convertedArr.sort(sortHelper1).reduce(reduceHelper, {});
};
당연히 이렇게 푸는 게 아니겠지 싶었지만 푸는 데 의의를 뒀다.
정규표현식은 무조건 어렵다는 생각에 아예 쓸 생각도 안했는데 여기서 replace메소드를 쓰는 정도는 연습해두는 게 맞았다. 그렇게 어려운 부분도 아니고
좋아요를 가장 많이 받은 사람의 풀이를 보니 엄청난 차이는 아니지만 어쨌거나 내 풀이보다 빨랐고, 결정적으로 함수형으로 풀어 코드의 가독성도 훨씬 좋고, 읽기에도 훨씬 직관적이었다.
아래는 다른 사람의 풀이를 참고하여 재구성한 코드이다.
const sortHelper1 = (a, b) => a.length - b.length;
const sortHelper2 = ([numOfA, idxOfA], [numOfB, idxOfB]) => idxOfA - idxOfB;
const reduceHelper = (acc, current, idx, origin) => {
current.forEach((num) => {
if (!acc.hasOwnProperty(num)) {
acc[num] = idx;
}
});
if (idx == origin.length - 1) {
return Object.entries(acc)
.sort(sortHelper2)
.map(([num, idx]) => parseInt(num));
}
return acc;
};
const solution = (s) => {
return JSON.parse(s.replace(/{/g, "[").replace(/}/g, "]"))
.sort(sortHelper1)
.reduce(reduceHelper, {});
};