치춘짱베리굿나이스
[백준] 7585 본문
Brackets
문제
As a C/Java programmer, you will be used to dealing with brackets. For the purpose of this problem, we will consider three type of bracket, round (), square [] and curly {}. As you know, every opening bracket must have a corresponding closing bracket, and brackets must be correctly nested.
This problem will give you some pieces of code. You have to check whether the brackets are legal or not. To keep things simple, there will be no brackets enclosed in quotes (which do not follow the standard rules, of course). New line characters have also been removed, so each line of input represents one piece of code to be checked.
입력
Input will consist of a number of lines of text (code), each one containing no more than 250 characters. The last line of input will contain just # - this line should be ignored. Each piece of code must be checked for legal brackets, and its status reported.
출력
If a line of code contains no brackets, or if all brackets are correctly paired and nested, the output should be Legal on a line on its own. If there are any errors, the output should be Illegal on a line on its own.
풀이
const brackets = () => {
let input = require("fs")
.readFileSync("/dev/stdin")
.toString()
.trim()
.split("\n");
let ans = [];
for (let str of input) {
if (str === "#") break;
let stack = [];
for (let c of str) {
if (
stack.length > 0 &&
((c === ")" && stack[stack.length - 1] === "(") ||
(c === "}" && stack[stack.length - 1] === "{") ||
(c === "]" && stack[stack.length - 1] === "["))
)
stack.pop();
else if (
c === "(" ||
c === ")" ||
c === "{" ||
c === "}" ||
c === "[" ||
c === "]"
)
stack.push(c);
}
if (stack.length) ans.push("Illegal");
else ans.push("Legal");
}
console.log(ans.join("\n"));
};
brackets();
반성회
괄호의 종류가 늘어난 괄호 쌍찾기문제..
'Javascript + Typescript > 자바스크립트로 알고리즘풀기' 카테고리의 다른 글
[백준] 10845 (0) | 2022.02.09 |
---|---|
[백준] 4992 (0) | 2022.02.09 |
[백준] 7568 (0) | 2022.02.09 |
[백준] 10814 (0) | 2022.02.09 |
[백준] 11650 (0) | 2022.02.09 |