프로그래머스 LEVEL 2(괄호 회전하기)
-
사용 언어 : javascript
-
해결 날짜 : 2022-10-02
- 해결 방법 :
- 회전시킨 문자열마다 stack의 값과 비교하여 올바른 괄호인지 검사
- str의 현재 char가 여는 괄호일 때, stack에 push()
- 닫는 괄호일 때, 현재 stack의 top을 pop() 후 그 값과 쌍이 맞지 않는 괄호라면 올바른 괄호가 아님
- 회고 :
- opening, closing을 key:value 한 쌍으로 묶으면 findIndex() 사용하지 않아도 됨
-
코드
const opening = ['(', '{', '[']; const closing = [')', '}', ']']; const isProperString = (str) => { const stack = []; let isProper = true; for (let i = 0; i < str.length; i++) { const current = str.charAt(i); if (opening.includes(current)) stack.push(current); else { const prev = stack.pop(); const prev_index = opening.findIndex((e) => e === prev); const current_index = closing.findIndex((e) => e === current); if(prev_index !== current_index) { isProper = false break; } } } return !stack.length && isProper; } function solution(s) { if (s.length % 2 === 1) return 0; let answer = 0; for (let i = 0; i < s.length; i++) { const current = s.slice(i) + s.slice(0, i); if (closing.includes(current.charAt(0)) || opening.includes(current.charAt(current.length - 1))) continue; if (isProperString(current)) answer++; } return answer; }
- 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges