알고리즘/programmers

[Programmers] 괄호 회전하기

꾸준함. 2021. 10. 6. 23:21

문제 링크입니다: https://programmers.co.kr/learn/courses/30/lessons/76502

 

코딩테스트 연습 - 괄호 회전하기

 

programmers.co.kr

반시계 방향으로 문자열을 회전시키면서 올바른 괄호 문자열을 확인해봐야하는 문제였습니다.

순서대로 스택을 넣었을 때 올바른 괄호 문자열이라면 마지막에 스택이 비어있어야합니다.

 

#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
bool isCorrect(string s)
{
stack<char> st;
for (char c : s)
{
if (!st.empty())
{
bool matched = false;
switch (st.top())
{
case '[':
if (c == ']')
{
matched = true;
st.pop();
}
break;
case '{':
if (c == '}')
{
matched = true;
st.pop();
}
break;
case '(':
if (c == ')')
{
matched = true;
st.pop();
}
break;
}
if (matched)
{
continue;
}
}
st.push(c);
}
return st.empty();
}
int solution(string s) {
int answer = 0;
for (int i = 0; i < s.length(); i++)
{
if (isCorrect(s))
{
answer++;
}
char c = s.front();
s = s.substr(1);
s += c;
}
return answer;
}
view raw .cpp hosted with ❤ by GitHub

 

개발환경:Visual Studio 2017

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

반응형