๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/Programmers

[C++/PGS] Lv.2 : ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ

by xxilliant 2025. 4. 23.
728x90
๋ฐ˜์‘ํ˜•

 

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr


ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ ˆ๋ฒจ 2 - ์›”๊ฐ„ ์ฝ”๋“œ ์ฑŒ๋ฆฐ์ง€ ์‹œ์ฆŒ2 ๊ธฐ์ถœ

s ๊ธธ์ด๊ฐ€ 1000์ดํ•˜๋กœ ์ •ํ•ด์ ธ์žˆ์–ด์„œ, ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค

ํ, ์Šคํƒ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ž˜ ์•Œ์•„์•ผ ํ•˜๋Š”๊ฒŒ ํฌ์ธํŠธ์ธ ๋ฌธ์ œ์ธ๋“ฏ

 

 

๋‚˜์˜ ํ’€์ด

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

int solution(string s) {
    int answer = 0;
    queue<int> q;
    queue<int> newq;
    for(int i=0; i<s.length(); ++i){
        q.push(s[i]);
        newq.push(s[i]);
    }
    
    for(int i=0; i<s.length(); ++i){
        stack<int> st;
        // stack์— ๋„ฃ์œผ๋ฉด์„œ ํ™•์ธ
        for(int i=0; i<s.length(); ++i){
            int a = newq.front();
            newq.pop();
            if(!st.empty() && st.top()=='(' && a==')') {
                st.pop();
            }
            else if(!st.empty() && st.top()=='[' && a==']') {
                st.pop();
            }
            else if(!st.empty() && st.top()=='{' && a=='}') {
                st.pop();
            }
            else st.push(a);
        }
        // ์œ„ ๊ณผ์ • ํ›„, ์Šคํƒ์ด ๋น„์–ด์žˆ์œผ๋ฉด ์ •๋‹ต
        if(st.empty()) answer++;
        // ๊ธฐ์กด ํ๋ฅผ ํšŒ์ „์‹œํ‚ด
        int topNum = q.front();
        q.pop();
        q.push(topNum);
        newq = q;
    }
    return answer;
}

 

728x90
๋ฐ˜์‘ํ˜•