-
4949) 균형잡힌 세상 c++백준코딩일기 2020. 11. 17. 10:32
문제 ) www.acmicpc.net/problem/4949
풀이 )
문제를 뒤에서부터 차분히 읽어보면,
1. 입력의 종료조건으로 맨 마지막에 점 하나(".")가 들어온다고 한다.
-> input.length() == 1 && input == "." 이면 break; 가 걸리도록2. 위의 경우가 아니면 계속해서 한 줄씩 입력을 받는다.
3. 왼쪽 소괄호와 왼쪽 대괄호가 들어오면 stack.push() 를해서 넣는다.
4. 오른쪽 소괄호를 만나면
-> 스택이 비어있지 않고, stack.top() == '(' 인 경우에만 pop() 을 한다.
만약 팝을 할 수 없는 상황이라면 flag = true 로 바꾸고 break5. 오른쪽 대괄호를 만나면
-> 스택이 비어있지 않고, stack.top() == '[' 인 경우에만 pop() 을 한다.
만약 팝을 할 수 없는 상황이라면 flag = true 로 바꾸고 break6. 가장 마지막으로 스택이 비어있고, flag = true 라면 yes 를, 아니라면 no 를 출력한다.
코드 )
#include <iostream> #include <stack> using namespace std; int main(void) { while(1) { string input; stack<char> s; getline(cin, input); int size = input.length(); bool flag = false; if(input.length()==1 && input == ".") break; for(int i=0; i<size; i++){ if(input[i] == '(' || input [i] == '[') s.push(input[i]); else if( input[i] == ')' ){ if( !s.empty() && s.top() == '(' ) s.pop(); else { flag = true; break; } } else if( input[i] == ']' ) { if( !s.empty() && s.top() == '[' ) s.pop(); else { flag = true; break; } } } if( s.empty() && !flag) cout << "yes\n"; else cout << "no\n"; } }
'백준코딩일기' 카테고리의 다른 글
2504) 괄호의 값 c++ (0) 2020.11.17 10799) 쇠막대기 c++ (0) 2020.11.17 10828) 스택 c++ (0) 2020.11.05 1158) 요세푸스 문제 (0) 2020.11.05 5397) 키로거 c++ (0) 2020.11.05