๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ(Level 2)

by ์•ˆ์ฃผํ˜• 2022. 4. 19.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ

 

programmers.co.kr

 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;


bool isOk(string s){
    stack<char> st;
    for(char c : s){
        if(c==']'||c==')'||c=='}'){
            if(st.empty()) return false;
            else if(c==']'&&st.top()=='[') st.pop();
            else if(c==')'&&st.top()=='(') st.pop();
            else if(c=='}'&&st.top()=='{') st.pop();
        }
        else st.push(c);
    }
    if(st.empty()) return true;
    return false;
}

int solution(string s) {
    int answer = 0;
    
    int len = s.length();
    
    while(len--){
        if(isOk(s)) answer++;
        string new_str = "";
        char s_back = s.front();
        new_str = s.substr(1,s.length()+1) + s_back;
        s = new_str;
    }
    
    return answer;
}

 

ํ’€์ด(11๋ถ„)

isOk๋ถ€๋ถ„์€ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ๋ฅผ ์ฐพ๋Š” ๋ถ€๋ถ„์ธ๋ฐ ์ด ๋ถ€๋ถ„๋งŒ ์š”๊ตฌํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ Level 2์— ์ด๋ฏธ ์žˆ์Šต๋‹ˆ๋‹ค.

 

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ(Level 2)

๋ฌธ์ œ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๊ด„ํ˜ธ๊ฐ€ ๋ฐ”๋ฅด๊ฒŒ ์ง์ง€์–ด์กŒ๋‹ค๋Š” ๊ฒƒ์€ '(' ๋ฌธ์ž๋กœ ์—ด๋ ธ์œผ๋ฉด ๋ฐ˜๋“œ์‹œ ์ง์ง€์–ด์„œ ')' ๋ฌธ์ž๋กœ ๋‹ซํ˜€์•ผ ํ•œ๋‹ค๋Š” ๋œป์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด "()()" ๋˜๋Š” "(())()" ๋Š” ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์ž…๋‹ˆ

dkswnkk.tistory.com

๊ด„ํ˜ธ๋ฅผ ํšŒ์ „ํ•˜๋Š” ๋ถ€๋ถ„์€ ๋งค๋ฒˆ ๋ฌธ์ž์—ด์˜ ์•ž ๊ธ€์ž๊ฐ€ ๋งจ ๋’ค๋กœ ๊ฐ€๊ฒŒ๋” ์ž๋ฅด๊ณ  ๋ถ™์—ฌ์„œ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€