Valid Parentheses (Level 2)

--- title: 'Valid Parentheses (Level 2)' author: '์ž„ํ›ˆ' date: 2024-10-14T13:53:35+09:00 category: ['POSTS'] tags: ['Javascript', 'Algorithm'] og_image: "/images/gamer.png" keywords: ['Javascript', 'Algorithm'] --- This exact problem appeared in a live coding test for the company I want to join. I had solved this problem three years ago while preparing for coding tests as a new graduate, but I couldn't remember it since it's been a while. It was so frustrating that I couldn't solve it halfway through, so I decided to review it. ```js function solution(s) { let stack = []; let obj = { '(': ')', '{':'}', '[':']' }; for (let i = 0; i < s.length; i++) { if (Object.keys(obj).includes(s[i])) { stack.push(s[i]); // Only push the left parentheses onto the stack. } else { let last = stack.pop(); // Pop the last item from the stack. if (s[i] !== obj[last]) { // If it doesn't match the correct closing bracket, return false. return false; } } } if (stack.length !== 0) { // If there's anything left in the stack, it means not all parentheses were closed, so return false. return false; } else { return true; // If the stack is empty, all parentheses were correctly matched, so return true. } } ```
ย 
--- title: '์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ (LV2)' author: '์ž„ํ›ˆ' date: 2024-10-14T13:53:35+09:00 category: ['POSTS'] tags: ['Javascript', 'Algorithm'] og_image: "/images/gamer.png" keywords: ['Javascript', 'Algorithm'] --- ๊ฐ€๊ณ  ์‹ถ์€ ํšŒ์‚ฌ ๋ผ์ด๋ธŒ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—์„œ ์ด ๋ฌธ์ œ๊ฐ€ ๊ทธ๋Œ€๋กœ ๋‚˜์™”๋‹ค. 3๋…„ ์ „, ์‹ ์ž… ์ค€๋น„ ํ•  ๋•Œ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์ค€๋น„ ํ•˜๋ฉด์„œ ๋ถ„๋ช…ํžˆ ํ’€์–ด๋ดค๋˜ ๋ฌธ์  ๋ฐ... ์˜ค๋ž˜ ๋˜์–ด์„œ ๊ธฐ์–ต์ด ๋‚˜์งˆ ์•Š์•˜๋‹ค. ์ค‘๊ฐ„์— ๋ชปํ‘ผ๊ฒŒ, ๋„ˆ๋ฌด ์•„์‰ฌ์› ๋‹ค. ๊ทธ๋ž˜์„œ ๋ณต๊ธฐ๋ฅผ ํ•ด๋ณด๋Š” ์ค‘์ด๋‹ค. ```js function solution(s) { let stack = []; let obj = { '(': ')', '{':'}', '[':']' }; for (let i = 0; i < s.length; i++) { if (Object.keys(obj).includes(s[i])) { stack.push(s[i]); // ์ขŒ์ธก์˜ ๊ด„ํ˜ธ๋งŒ stack์— ๋„ฃ๋Š”๋‹ค. } else { let last = stack.pop(); // stack ๋ฐฐ์—ด์˜ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์„ ๋นผ์„œ if (s[i] !== obj[last]) { // ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์— ๋งž์ถฐ๋ณด๊ณ , ์•„๋‹ˆ๋ฉด false return false; } } } if (stack.length !== 0) { // stack์— ์–ด๋–ค ๊ฐ’์ด ๋‚จ์•„ ์žˆ๋‹ค๋ฉด, ๊ด„ํ˜ธ๊ฐ€ ๋ชจ๋‘ ๋‹ซํžˆ์ง€ ์•Š์•˜๋‹ค๋Š” ์˜๋ฏธ๊ฐ€ ๋œ๋‹ค. ๊ณ ๋กœ, false return false; } else { return true; // stack์ด ๋ชจ๋‘ ์ œ๊ฑฐ๊ฐ€ ๋˜์—ˆ๋‹ค๋Š” ๋œป์€, ๊ด„ํ˜ธ๊ฐ€ ๋ชจ๋‘ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋‹ซํ˜”๋‹ค๋Š” ์˜๋ฏธ, ๊ณ ๋กœ true } } ```