-
4889) 안정적인 문자열 c++백준코딩일기 2020. 11. 17. 10:43
문제 ) www.acmicpc.net/problem/4889
풀이 )
문자열은 짝수개의 형태로 입력이 들어오게 되므로,
{} 쌍을 모두 지우고 나면 짝수개의 }} 형태, {{ 형태 또는 }{ 형태만 남는다.}} 형태과 {{ 형태의 경우 하나만 뒤집어 주면 되므로 최종 출력값인 ans 에 1을 더하고,
}{ 형태의 경우 두 개를 다 뒤집어야하므로 ans +2 를 해준다.
코드 )
#include <iostream> #include <stack> #include <string> using namespace std; string input; stack<char> S; //ansNum 출력값에 넘버링해주는 변수 int ansNum = 1, ans; int main(void) { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); while (1) { cin >> input; ans = 0; for (int i = 0; i < input.length(); i++) { if (input[i] == '{') S.push(input[i]); else if (input[i] == '}') { if (S.empty() || S.top() != '{') S.push(input[i]); else S.pop(); } else // '-' 끝내는 부호가 들어왔을 경우 return 0; } while (!S.empty()) { char t = S.top(); S.pop(); // }{ 의 경우 if (S.top() != t) ans += 2; // }} , {{ 의 형태일 경우 else ans += 1; S.pop(); } cout << ansNum++ << ". " << ans << '\n'; } }
'백준코딩일기' 카테고리의 다른 글
17298) 오큰수 c++ (0) 2020.11.19 9093) 단어 뒤집기 c++ (0) 2020.11.19 2504) 괄호의 값 c++ (0) 2020.11.17 10799) 쇠막대기 c++ (0) 2020.11.17 4949) 균형잡힌 세상 c++ (0) 2020.11.17