알고리즘/프로그래머스
프로그래머스 괄호 회전하기 c++
이영재의오른발
2022. 12. 4. 22:09
반응형
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
bool checkString(string str) {
stack<char> stk;
bool check = true;
for(int i=0; i<str.length(); i++) {
if(str[i] == '[' || str[i] == '(' || str[i] == '{') {
stk.push(str[i]);
}
else {
if(stk.empty()) { check = false; }
if(str[i] == ']' && stk.top() != '[') { check = false; }
if(str[i] == ')' && stk.top() != '(') { check = false; }
if(str[i] == '}' && stk.top() != '{') { check = false; }
stk.pop();
}
}
if(!stk.empty()) {
check = false;
}
return check;
}
int turnString(string s) {
string str = s;
int result = 0;
for(int i=0; i<s.length(); i++) {
string tmp = "";
for(int j=1; j<s.length(); j++) {
tmp += str[j];
}
tmp += str[0];
str = tmp;
if(checkString(tmp)) { result++; }
}
return result;
}
int solution(string s) {
int answer = -1;
answer = turnString(s);
return answer;
}
**
프로그램 흐름도
1. 왼쪽으로 문자열을 돌림 (문제에서 돌린다는 표현은 하나씩 이동함을 뜻함)
2. 돌린 문자열의 괄호배치가 정상적인지 검사
3. 정상적일경우 결과값에 1더해줌
**
스택을 사용하면 쉽게 풀리는 간단한 문제
비슷한 유형이 많으니 이런 유형이 나왔을때는 스택을 떠올리자
728x90
반응형