01-08 08:57
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Programmers] ์ง์ง€์–ด ์ œ๊ฑฐํ•˜๊ธฐ - JAVA (Stack/Queue) ๋ณธ๋ฌธ

Algorithm/Programmers

[Programmers] ์ง์ง€์–ด ์ œ๊ฑฐํ•˜๊ธฐ - JAVA (Stack/Queue)

miinsun 2022. 5. 8. 18:14

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

์ง์ง€์–ด ์ œ๊ฑฐํ•˜๊ธฐ๋Š”, ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์„ ๊ฐ€์ง€๊ณ  ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

๋จผ์ € ๋ฌธ์ž์—ด์—์„œ ๊ฐ™์€ ์•ŒํŒŒ๋ฒณ์ด 2๊ฐœ ๋ถ™์–ด ์žˆ๋Š” ์ง์„ ์ฐพ์Šต๋‹ˆ๋‹ค. ๊ทธ๋‹ค์Œ, ๊ทธ ๋‘˜์„ ์ œ๊ฑฐํ•œ ๋’ค, ์•ž๋’ค๋กœ ๋ฌธ์ž์—ด์„ ์ด์–ด ๋ถ™์ž…๋‹ˆ๋‹ค.
์ด ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ด์„œ ๋ฌธ์ž์—ด์„ ๋ชจ๋‘ ์ œ๊ฑฐํ•œ๋‹ค๋ฉด ์ง์ง€์–ด ์ œ๊ฑฐํ•˜๊ธฐ๊ฐ€ ์ข…๋ฃŒ๋ฉ๋‹ˆ๋‹ค.

๋ฌธ์ž์—ด S๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ง์ง€์–ด ์ œ๊ฑฐํ•˜๊ธฐ๋ฅผ ์„ฑ๊ณต์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด ์ฃผ์„ธ์š”.
์„ฑ๊ณต์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์œผ๋ฉด 1์„, ์•„๋‹ ๊ฒฝ์šฐ 0์„ ๋ฆฌํ„ดํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, ๋ฌธ์ž์—ด S = baabaa ๋ผ๋ฉด
b aa baa → bb aa → aa →
์˜ ์ˆœ์„œ๋กœ ๋ฌธ์ž์—ด์„ ๋ชจ๋‘ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ 1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿšซ ์ œํ•œ ์‚ฌํ•ญ

  • ๋ฌธ์ž์—ด์˜ ๊ธธ์ด : 1,000,000์ดํ•˜์˜ ์ž์—ฐ์ˆ˜
  • ๋ฌธ์ž์—ด์€ ๋ชจ๋‘ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

s result
baabaa 1
cdcd 0

 

  1. ์ž…์ถœ๋ ฅ ์˜ˆ
    • ์œ„์˜ ์˜ˆ์‹œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.
  2. ์ž…์ถœ๋ ฅ ์˜ˆ
    • ๋ฌธ์ž์—ด์ด ๋‚จ์•„์žˆ์ง€๋งŒ ์ง์ง€์–ด ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์—ด์ด ๋” ์ด์ƒ ์กด์žฌํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— 0์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

class Solution
{
    public int solution(String s)
    {
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()){	// ๋ฌธ์ž์—ด ํ•˜๋‚˜์”ฉ ๊ฒ€์‚ฌ
            if(!stack.isEmpty()){	// ์Šคํƒ์ด ๋น„์–ด์žˆ์ง€ ์•Š์„๋•Œ๋งŒ ์ง ๊ฒ€์‚ฌ
                if(c == stack.peek()){	// ์ง์ด ๋งž์œผ๋ฉด ๋‘˜๋‹ค ์ œ๊ฑฐ
                    stack.pop();
                }
                else	// ์ง์ด ๋งž์ง€ ์•Š์œผ๋ฉด, ์ถ”๊ฐ€
                    stack.add(c);
            }
            else{    // ๋น„์–ด์žˆ์„ ๋•Œ
                stack.add(c);
            }
        }
        
        int answer = 1;
        if(!stack.isEmpty())
            answer = 0;

        return answer;
    }
}
Comments