Problem Solving/Baekjoon
[백준] 5002 도어맨 - Greedy / Java
graycode
2023. 8. 22. 20:47
• 문제 링크
5002번: 도어맨
첫째 줄에 정인이가 기억할 수 있는 가장 큰 차이 X<100이 주어진다. 둘째 줄에는 줄을 서 있는 순서가 주어진다. W는 여성, M은 남성을 나타내며, 길이는 최대 100이다. 가장 왼쪽에 있는 글자가 줄
www.acmicpc.net
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int x = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder(br.readLine());
int m = 0, w = 0;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == 'M') m++;
else w++;
if (Math.abs(m - w) > x) {
if (c == 'M') m--;
else w--;
if (i == sb.length() - 1 || c == sb.charAt(i + 1)) break;
else {
sb.setCharAt(i, sb.charAt(i + 1));
sb.setCharAt(i + 1, c);
i--;
}
}
}
bw.write(String.valueOf(m + w));
bw.flush();
}
}