[백준]4889.안정적인 문자열

bywow·2021년 4월 8일
0

algorithm

목록 보기
2/2

안정적인 문자열

🔑문제 유형

stack & 구현

🛠 시행 착오

빈 문자열 체크
처음엔 케이스 별로 나눠보려고 함 
- {{{{ 만 있는 케이스 -> 절반만 반대로 돌리면 되니 스택 사이즈/2
- }}}} 만 있는 케이스 -> 절반만 반대로 돌리면 되니 카운트 사이즈/2
- }{ 둘다 있는 케이스 (여기가...매우 더러워짐😂)
  -- }가 더 많은 케이스 }}}}}{ -> 더 많은 쪽은 위에 기준 적용. 적은 쪽은 갯수만큼 다 돌려야하므로 ... x2
  -- {가 더 많은 케이스 }{{{{{ -> 더 많은 쪽은 위에 기준 적용. 적은 쪽은 갯수만큼 다 돌려야하므로 ... x2
  -- }{ 갯수 같음 
     --- }{ 한번 -> 한쪾 갯수*2
     --- }}{{ 한번 이상 -> 서로 마주보게 해주면 되므로 /2 (근데 홀수일때는 또...다름)

😅 포기..
다른 사람의 아이디어 차용! } 나오면 { 로 바꿔서 넣는다
{{만 남음으로 } 나온 횟수 + 스택 갯수 /2 해줌

📃 코드1 (실패)

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

stack <char> s;
int check(string input){
		if(!input.size()) return 0;
		
    int cnt=0;
    for(char c: input){
         if(c=='{') s.push(c);
         else if(c=='}') {
             if(s.empty()) cnt++;
             else s.pop();
         }
    }
    // }{
    if(cnt && !s.empty()){
        if(cnt > s.size()) return (cnt-s.size())/2 + s.size()*2;
        else return (s.size()-cnt)/2 + cnt*2;
    }
    // {{
    else if(!s.empty())return s.size()/2;
    // }}
    else if(cnt) return cnt/2;
    else return cnt;
}

int main(){
    int fin=0;
    while(++fin){
        while( !s.empty() ) s.pop();
        string input;int cnt=0;

        cin>>input;
        if( input.find('-')!=string::npos) break;
        cout<<fin<<". "<<check(input)<<"\n";
    }
    return 0;
}

📃 코드2 (성공)

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

stack <char> s;
int check(string input){
    int cnt=0;
    if(!input.size()) return 0;
    for(char c: input){
         if(c=='{'){ 
             s.push(c);
         }
         else if(c=='}') {
             if(s.empty()) {
                 cnt++;
                 s.push('{');
             }
             else s.pop();
         }
    }
    return cnt+s.size()/2;
}

int main(){
    int fin=0;
    while(++fin){
        while( !s.empty() ) s.pop();
        string input; int cnt=0;
        cin>>input;

        if(input.find('-')!=string::npos) break;
        cout<<fin<<". "<<check(input)<<"\n";
    }
    return 0;
}
profile
어제보다 오늘 더 알기

0개의 댓글