https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWWxqfhKAWgDFAW4
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
배열로 카운팅 하면 쉽게 풀 수 있다.
<JAVA>
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
int countArr[] = new int[4];
char c;
String S = br.readLine();
int count = 0;
boolean isCheck = true;
for (int i = 0; i < S.length() && isCheck; i++) {
c = S.charAt(i);
switch (c) {
case 'c':
countArr[0]++;
break;
case 'r':
countArr[1]++;
countArr[0]--;
if (countArr[0] == -1) {
isCheck = false;
}
break;
case 'o':
countArr[2]++;
countArr[1]--;
if (countArr[1] == -1) {
isCheck = false;
}
break;
case 'a':
countArr[3]++;
countArr[2]--;
if (countArr[2] == -1) {
isCheck = false;
}
break;
case 'k':
countArr[3]--;
if (countArr[3] == -1) {
isCheck = false;
}
break;
}
count = Math.max(count, countArr[0] + countArr[1] + countArr[2] + countArr[3]);
}
if (countArr[0] != 0 || countArr[1] != 0 || countArr[2] != 0 || countArr[3] != 0) {
isCheck = false;
}
if (!isCheck) {
count = -1;
}
System.out.printf("#%d %d\n", t, count);
}
}
}
<C++>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
int countArr[4] = { 0 };
char c;
string s;
cin >> s;
int count = 0;
bool isCheck = true;
for (int i = 0; i < s.length() && isCheck; ++i) {
c = s[i];
switch (c) {
case 'c':
++countArr[0];
break;
case 'r':
++countArr[1];
--countArr[0];
if (countArr[0] == -1) {
isCheck = false;
}
break;
case 'o':
++countArr[2];
--countArr[1];
if (countArr[1] == -1) {
isCheck = false;
}
break;
case 'a':
++countArr[3];
--countArr[2];
if (countArr[2] == -1) {
isCheck = false;
}
break;
case 'k':
--countArr[3];
if (countArr[3] == -1) {
isCheck = false;
}
break;
}
count = max(count, countArr[0] + countArr[1] + countArr[2] + countArr[3]);
}
if (countArr[0] != 0 || countArr[1] != 0 || countArr[2] != 0 || countArr[3] != 0) {
isCheck = false;
}
if (!isCheck) {
count = -1;
}
cout << "#" << t << " " << count << "\n";
}
}
'알고리즘 > SWEA' 카테고리의 다른 글
4050. 재관이의 대량 할인 (0) | 2019.10.28 |
---|---|
6782. 현주가 좋아하는 제곱근 놀이 (0) | 2019.10.15 |
7396. 종구의 딸이름 짓기 (0) | 2019.10.08 |
7701. 염라대왕의 이름 정렬 (0) | 2019.10.08 |
3349. 최솟값으로 이동하기 (0) | 2019.10.07 |