๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 3986_์ข‹์€ ๋‹จ์–ด

๋ฟŒ์•ผ._. 2023. 8. 23. 10:08

Silver IV

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/3986)

< ์ข‹์€ ๋‹จ์–ด >

 

๋ฌธ์ œ ํ’€์ด 

 

Stack์„ ์‚ฌ์šฉํ•ด์„œ A๋ผ๋ฆฌ ๋˜๋Š” B๋ผ๋ฆฌ ์Œ์„ ์ง€์–ด ์—ฐ๋‹ฌ์•„ ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class _3986_ { // ์ข‹์€ ๋‹จ์–ด

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(bf.readLine());

		int answer = 0;

		Stack<Character> stack = new Stack<>();
		for (int i = 0; i < n; i++) {
			String str = bf.readLine();
			int idx = 0;
			while (idx < str.length()) {
				if (!stack.isEmpty()) {
					if (stack.peek() == str.charAt(idx)) {
						stack.pop();
					} else {
						stack.add(str.charAt(idx));
					}
				} else {
					stack.add(str.charAt(idx));
				}
				idx += 1;
			}
			if (stack.isEmpty()) {
				answer += 1;
			}
			stack.clear();
		}
		System.out.println(answer);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ๋‹จ์–ด์˜ ์ˆ˜
answer : ์ข‹์€ ๋‹จ์–ด์˜ ์ˆ˜
stack : Stack <Character>
str : A์™€ B๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด

 

- ๋‹จ์–ด์˜ ์ˆ˜ (n) ์ž…๋ ฅ

- ๋‹จ์–ด์˜ ์ˆ˜(n) ๋งŒํผ A์™€ B๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด(str) ์ž…๋ ฅ

: ๋‹จ์–ด(str)๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ

1) stack์ด ๋น„์–ด์žˆ๋‹ค๋ฉด ์ถ”๊ฐ€

2) stack์— ๊ฐ’์ด ์žˆ์œผ๋ฉด์„œ stack.peek() ๊ฐ’์ด ํ˜„์žฌ ๋„ฃ์œผ๋ ค๋Š” ๊ฐ’๊ณผ ๊ฐ™๋‹ค๋ฉด ์Œ์„ ์ง€์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ pop

3) stack์— ๊ฐ’์ด ์žˆ์œผ๋ฉด์„œ stack.peek() ๊ฐ’์ด ํ˜„์žฌ ๋„ฃ์œผ๋ ค๋Š” ๊ฐ’๊ณผ ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด stack์— ์ถ”๊ฐ€

: ์ˆœํšŒ ํ›„ stack์˜ ๊ฐ’์ด ๋น„์–ด์žˆ์œผ๋ฉด ์ข‹์€ ๋‹จ์–ด๋ž€ ๋œป์ด๋ฏ€๋กœ answer +1

- ์ข‹์€ ๋‹จ์–ด์˜ ์ˆ˜(answer) ์ถœ๋ ฅ