'Bracket2'에 해당되는 글 1건

  1. 2022.01.03[BRACKETS2] Mismatched Brackets

Java 로 풀어보는 알고리즘입니다. 📖
코딩테스트를 대비하여 JAVA1.8 부터 제공되는 함수형 API 는 사용하지 않았습니다.

문제 : https://www.algospot.com/judge/problem/read/BRACKETS2

 

algospot.com :: BRACKETS2

Mismatched Brackets 문제 정보 문제 Best White is a mathematics graduate student at T1 University. Recently, he finished writing a paper and he decided to polish it. As he started to read it from the beginning, he realized that some of the formulas ha

www.algospot.com

 

풀이입니다. 🤔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Map<Character, Character> brackets = new HashMap<>();
        brackets.put('['']');
        brackets.put('{''}');
        brackets.put('('')');
 
        int cases = scanner.nextInt();
        while (cases-- > 0) {
            String line = scanner.next();
            System.out.println(isRight(line, brackets) ? "YES" : "NO");
        }
    }
 
    private static boolean isRight(String line, Map<Character, Character> brackets) {
        Stack<Character> stack = new Stack<>();
        for (char c : line.toCharArray()) {
            if (brackets.containsKey(c)) stack.push(c);
            else {
                if (stack.isEmpty()) return false;
                if (c != brackets.get(stack.pop())) return false;
            }
        }
 
        return stack.isEmpty();
    }
}
cs

 

 

이 포스트를 읽어주셔서 감사합니다. 🙇🏻‍♂️

반응형

'개발이야기 > 알고스팟' 카테고리의 다른 글

[NQUEEN] N-Queen  (0) 2022.01.04
[FIXPAREN] Mismatched Parenthesis  (0) 2022.01.04
[SHISENSHO] Shisen-sho  (0) 2022.01.03
[WEEKLYCALENDAR] Weekly Calendar  (0) 2022.01.03
[CLOCKSYNC] Synchronizing Clocks  (0) 2022.01.02
Posted by N'