백준

백준 2504 괄호의 값, c++

2024. 2. 28. 14:39

 

 

 

처음 작성한 코드는 다음과 같다.

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main(){
    string str;
    cin >> str;
    
    stack<int> s;
    int count = 0;
    for(int i=0; i<str.length(); i++) {
        if(s.empty()==true){
            s.push(str[i]);   
            continue;
        }     
        
        if( str[i]=='(' || str[i]=='[' )
            s.push(str[i]);
        else if( str[i]==')' ){
            if(s.top()!='('){
                count = 0;
                break;
            }
            if(s.size()>2){
                if(count==0)
                    count +=2;
                else
                    count *=2;
            }
            else
                count += 2;
            s.pop();
        }
        else if( str[i]==']' ){
            if(s.top()!='['){
                count = 0;
                break;
            }
            if(s.size()>2){
                if(count==0)
                    count +=3;
                else
                    count *=3;
            }
            else
                count += 3;
            s.pop();            
        }        
    }
    
    cout << count;
    
    return 0;
}

하지만 틀렸다는 결과가 나왔다.

 

 

 

수정한 코드는 다음과 같다.

몇 가지 조건을 생각하지 못했다.

1. for문이 모두 끝나고 stack에 문자가 남아있으면 0을 출력한다.

2. 곱하기로 계산되는 것들은 temp로 계산하고 나중에 한번에 더해준다.

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main(){
    string str;
    cin >> str;
    
    stack<char> s;
    int count = 0;
    int temp = 1;
    
    for(int i=0; i<str.length(); i++) {
        if(str[i]=='('){
            temp*=2;
            s.push('(');
        }
        else if(str[i]=='['){
            temp*=3;
            s.push('[');
        }
        else if( str[i]==')' ){
            if(s.empty() || s.top()!='('){
                count = 0;
                break;
            }
            if(str[i-1]=='('){
                count+=temp;
                temp/=2;
                s.pop();
            }
            else{
                temp/=2;
                s.pop();
            }
        }
        else if( str[i]==']' ){
            if(s.empty() || s.top()!='['){
                count = 0;
                break;
            }
            if(str[i-1]=='['){
                count+=temp;
                temp/=3;
                s.pop(); 
            }
            else{
                temp/=3;
                s.pop(); 
            }           
        }        
    }
    
    if(!s.empty())
        count = 0;
    
    cout << count;
    
    return 0;
}

 

 

 

 

 

'백준' 카테고리의 다른 글

백준 3085 사탕 게임, c++  (0) 2024.02.29
백준 1789 수들의 합, c++  (0) 2024.02.29
백준 2910 빈도 정렬, c++  (0) 2024.02.27
백준 2693 N번째 큰 수, c++  (0) 2024.02.27
백준 2460 지능형 기차 2, c++  (1) 2024.02.27