๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • ์žฅ์›์ต ๊ธฐ์ˆ ๋ธ”๋กœ๊ทธ
๐Ÿ’ป Computer Science/- Data Structure, Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜ PS] ๋ฐฑ์ค€ 3986 ์ข‹์€ ๋‹จ์–ด ์ž๋ฐ” ๋ฌธ์ œ ํ’€์ด

by Wonit 2021. 1. 15.

๋ฌธ์ œ

ํ•ด๋‹น ํฌ์ŠคํŒ…์€ ๋ฐฑ์ค€์˜ ๋ฐฑ์ค€ ๋ฒˆ ๋ฌธ์ œ ๋งํฌ ์˜ ์ ‘๊ทผ๊ณผ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•œ ๊ธ€ ์ž…๋‹ˆ๋‹ค.
์ •๋‹ต ์†Œ์Šค ์ฝ”๋“œ๋ฅผ ํ™•์ธํ•˜์‹œ๋ ค๋ฉด solve url ์—์„œ ํ™•์ธ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ

์˜ˆ์ œ ์ž…๋ ฅ & ์ถœ๋ ฅ

ํ•ด๊ฒฐ๋ฒ•

์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ•ด์•ผ ํ•˜๋Š”์ง€์™€ ์–ด๋–ค ํŠธ๋ฆญ์„ ํ”ผ์• ํ– ํ• ์ง€๋ฅผ ์ƒ๊ฐํ•ด๋ณด๋Š” ์˜ค๋‹ต ํ›„๋ณด๋ฅผ ๋‚˜๋ˆ  ์ƒ๊ฐํ•ด๋ณด์ž.

์ ‘๊ทผ๋ฒ•

์šฐ์„  ํ•ด๋‹น ๋ฌธ์ œ๋Š” ์Šคํƒ์„ ์ด์šฉํ•ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.


ABAB๋ผ๋Š” ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•˜๋ ค๋ฉด A์™€ B๊ฐ€ ์„œ๋กœ ๊ฐ™๊ณ , AA์™€ BB๊ฐ€ ์„œ๋กœ ๊ฐ™๋‹ค.

 


ํ•˜์ง€๋งŒ A์™€ A๋ฅผ ์•„์น˜ํ˜•์œผ๋กœ ์„ ์„ ๋งŒ๋“ค๊ณ  B์™€ B๋ฅผ ์•„์น˜ํ˜•์œผ๋กœ ์„ ์„ ๋งŒ๋“ค๋ฉด ์„œ๋กœ ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์กด์žฌํ•˜๋ฏ€๋กœ ์˜ค๋‹ต์ด๋‹ค.


ํ•˜์ง€๋งŒ AABB๋ฅผ ์ƒ๊ฐํ•ด๋ณด์ž.


A์™€ A๋ฅผ ์•„์น˜ํ˜•์œผ๋กœ ์„ ์„ ๋งŒ๋“ค๊ณ  B์™€ B๋ฅผ ์•„์น˜ํ˜•์œผ๋กœ ์„ ์„ ๋งŒ๋“ค๋ฉด ์„œ๋กœ ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์—†์œผ๋ฏ€๋กœ ์ •๋‹ต์ด ๋œ๋‹ค.

 

์ด๋Ÿฐ ํ•ด๊ฒฐ๋ฒ•์„ ์Šคํƒ๊ณผ ์—ฐ๊ด€์ง€์–ด ์ƒ๊ฐํ•ด๋ณด์ž


์Šคํƒ์— ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ push ํ•˜๊ณ  ๊ทธ ๋‹ค์Œ ์ธ๋ฑ์Šค๋ฅผ ๋‚จ์€ ์Šคํƒ์˜ ์›์†Œ์™€ ๋น„๊ตํ•ด์„œ ๊ฐ™์œผ๋ฉด pop๋ฅผ ํ•˜๋Š” ์‹์œผ๋กœ ๋ฌธ์ž์—ด์˜ ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ๊ฒ€์‚ฌํ•œ๋‹ค.

์˜ค๋‹ต ํ›„๋ณด

  1. ๋ฌธ์ž์—ด ๊ฒ€์ฆ์ด ๋๋‚ฌ๋Š”๋ฐ, stack์ด ๋น„์–ด์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ

ํ•ด๋‹น ๋ฌธ์ œ์˜ ์˜ค๋‹ต ํ›„๋ณด๋Š” ํ•˜๋‚˜๋‹ค.
๊ด„ํ˜ธ ๋ฌธ์ œ ์ฒ˜๋Ÿผ ๋ฌธ์ž์—ด๋“ค์„ ๊ด„ํ˜ธ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ์‰ฝ๋‹ค.
๊ด„ํ˜ธ ๋ฌธ์ œ์™€ ์ ‘๊ทผ ๋ฐฉ๋ฒ•๊ณผ ๋กœ์ง์ด ๋น„์Šทํ•˜๋‹ค.

์ •๋‹ต ์ฝ”๋“œ

import java.util.Scanner;
import java.util.Stack;

public class Main {
  public static void main(String[] args) {

    int answer = 0;

    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    String[] words = new String[n];
    for(int i = 0; i < n; i++) {
      words[i] = input.next();
    }

    for(String word : words) {
      Stack<Character> stack = new Stack<>();
      check(stack, word);

      if(stack.isEmpty()) answer++;
    }
    System.out.println(answer);
  }

  // stack๊ณผ ๋น„๊ตํ•˜๋Š” ๋ฉ”์„œ๋“œ
  private static void check(Stack<Character> stack, String word) {
    stack.push(word.charAt(0)); // ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๋Š” ๋ฐ”๋กœ stack์— ์ถ”๊ฐ€์‹œํ‚จ๋‹ค.

    /* 2๋ฒˆ์งธ ๋ฌธ์ž๋ถ€ํ„ฐ ์Šคํƒ์ด ๋น„์–ด์žˆ์ง€ ์•Š๋Š” ์„ ์—์„œ ๋ฐ˜๋ณต์„ ๋Œ๋ฉฐ pop๊ณผ push๋ฅผ ๋ฐ˜๋ณต*/
    for(int i = 1; i < word.length(); i++) {
      if(!stack.isEmpty() && stack.peek() == word.charAt(i)){
        stack.pop();
        continue;
      }
      stack.push(word.charAt(i));
    }
  }
}

์ •๋‹ต ์†Œ์Šค ์ฝ”๋“œ๋ฅผ ํ™•์ธํ•˜์‹œ๋ ค๋ฉด solve url ์—์„œ ํ™•์ธ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

๋Œ“๊ธ€