티스토리 뷰
문제 링크
https://algospot.com/judge/problem/read/BRACKETS2
algospot.com :: BRACKETS2
Mismatched Brackets 문제 정보 문제 Best White is a mathematics graduate student at T1 University. Recently, he finished writing a paper and he decided to polish it. As he started to read it from the beginning, he realized that some of the formulas have problems:
algospot.com
문제 설명
-종만북에서 '짝이 맞지 않는 괄호' 라는 이름으로 소개된 문제이다.
-괄호들로 이루어진 문자열이 주어질 때 괄호들이 짝을 이루는지/ 안 이루는지를 판별해주면 된다.
-짝이 맞는 괄호 문자열의 예시-> (([[))
-짝이 맞지 않는 괄호 문자열의 예시 -> {)(}
문제 풀이
-스택을 적극 활용한다.
-우선 맞는 여는 괄호들 ( , {, [ 은 스택에 push
-닫는 괄호들이 들어올 때 현재 스택의 top과 합이 맞는지 비교 - > 여기에서 아스키 코드를 적극 활용했다.
-만약 () {} []과 같이 합이 맞다면 현재 top에 있는 요소를 pop해준다.
-모든 문자열을 탐색해주고, 스택이 비어 있다면 짝이 맞는 괄호 문자열/ 비어 있지 않다면 짝이 맞지 않는 괄호 문자열
소스 코드
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
int c;
int results[105] = { 0, };
int index = 0;
cin >> c;
while (c--) {
stack<char> temp;
string given;
cin >> given; //문자열 입력받음
for (int i = 0; i < given.length(); i++) {
char now = given[i];
if (now == '(' || now == '{' || now == '[') { //열리는 괄호
temp.push(given[i]);
}
else { //닫히는 괄호
if (temp.empty() == false) {
int value = now + temp.top(); //스택의 top과 현재 들어온 값 더해줌
if (value == 248 || value == 184 || value == 81) { //아스키 코드로 합 맞음
temp.pop();
}
else { //합이 안맞음
temp.push(now);
break;
}
}
else { //처음부터 닫히는 괄호가 들어올 때
temp.push(now);
break;
}
}
}
if (temp.empty() == true) {
results[index] = 1;
}
else {
results[index] = 0;
}
index++;
}
for (int i = 0; i < index; i++) {
if (results[i] == 0) {
cout << "NO" << endl;
}
else {
cout << "YES" << endl;
}
}
return 0;
}
참고 : 괄호들의 아스키 코드 값
{ | 123 | [ | 91 | ( | 40 |
} | 125 | ] | 93 | ) | 41 |
'Problem Solving' 카테고리의 다른 글
BOJ 2623 : 음악 프로그램 (0) | 2020.08.24 |
---|---|
BOJ 17828 : 문자열 화폐 (0) | 2020.08.24 |
BOJ 18866 : 젊은 날의 생이여 (0) | 2020.08.23 |
LRU(Least Recently Used) Algorithm (0) | 2020.02.09 |
BOJ 10769 : 행복한지 슬픈지 (0) | 2019.07.21 |
- Total
- Today
- Yesterday
- 파이썬
- Javascript
- vscode
- SQL
- cipher suite
- 스택
- Til
- Event Sourcing
- 위상정렬
- 우선순위큐
- BOJ
- Python
- 백준
- django testcase
- Remote
- docker-compose update
- 이것도모르면바보
- 힙
- requests
- 그리디
- jwt
- 프로그래머스
- 코딩테스트
- django test
- 최대한 간략화하기
- SSL
- 삽질
- endl을절대쓰지마
- 불필요한 값 무시하기
- factory_pattern
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |