algorithm
[프로그래머스] 괄호 회전하기
지제로
2022. 9. 13. 23:11
풀이 과정
1. tmp라는 문자열을 만들어 문자를 회전시킨다. - substr()을 사용하여 범위를 지정해주었다.
2. checkBracket()라는 함수를 만들어 해당 tmp가 맞게 되어있는지 true, false로 반환해주었다.
3. checkBracket함수는 '(', '[', '{' 인 문자가 들어오면 push하고, ')', '}', ']' 인 문자가 들어오면 pop을 해주는 형식으로 구현했다.
+ '(', '{', '[' 인 문자가 없는 상태에서 pop을 할 수 있기에 조건을 추가했다.
#include <string>
#include <vector>
#include <stack>
using namespace std;
stack<char> st;
char small[]={'(',')'};
char middle[]={'[',']'};
char large[]={'{','}'};
bool checkBracket(string s){
for(int i=0;i<s.length(); i++){
if(s[i]==small[0] || s[i]==middle[0] || s[i]==large[0])
st.push(s[i]);
else if(st.empty()) //위에가 아닌데 빈 경우
return false;
else{
if(st.top()==small[0] && s[i]==small[1])
st.pop();
else if(st.top()==middle[0] && s[i]==middle[1])
st.pop();
else if(st.top()==large[0] && s[i]==large[1])
st.pop();
} //내 짝이 위에 있을 때 pop
}
if(st.empty())
return true;
return false;
}
int solution(string s) {
int answer = 0;
string first=s;
string tmp="";
for(int i=0;i<s.length();i++){
tmp=first.substr(i+1,s.length()-1)+first.substr(0,i+1);
//printf("tmp: %s \n", tmp.c_str());
if(checkBracket(tmp))
answer++;
}
return answer;
}