─━ IT ━─

[해커랭크, HackerRank] [JAVA] Stacks: Balanced Brackets

DKel 2021. 3. 24. 08:10
반응형
 

Stacks: Balanced Brackets | HackerRank

Given a string containing three types of brackets, determine if it is balanced.

www.hackerrank.com

코딩테스트 연습 - Balanced Brackets

설명

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].

Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and ().

A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ].

Some examples of balanced brackets are []{}(), [({})]{}() and ({(){}[]})[].

By this logic, we say a sequence of brackets is considered to be balanced if the following conditions are met:

  • It contains no unmatched brackets.
  • The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.

Given  strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, print YES on a new line; otherwise, print NO on a new line.

제한사항

 

  • Each character in the sequence will be a bracket (i.e., {, }, (, ), [, and ]).

 

 

 

소스코드

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'isBalanced' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts STRING expression as parameter.
     */

    public static String isBalanced(String expression) {
        Stack<Character> stack = new Stack<>();
        expression = expression.replaceAll(" ", "");
        char[] chars = expression.toCharArray();

        for (char c : chars) {
            if (stack.isEmpty()) {
                if (c == ']' || c == '}' || c == ')' || c == '>') {
                    return "NO";
                } else {
                    stack.push(c);
                }
            } else {
                char item = stack.peek();
                if (item == '[' && c == ']') {
                    stack.pop();
                } else if (item == '{' && c == '}') {
                    stack.pop();
                } else if (item == '(' && c == ')') {
                    stack.pop();
                } else if (item == '<' && c == '>') {
                    stack.pop();
                } else {
                    if (c == ']' || c == '}' || c == ')' || c == '>') {
                        return "NO";
                    } else {
                        stack.push(c);
                    }
                }
            }
        }
        return stack.isEmpty() ? "YES" : "NO";
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, t).forEach(tItr -> {
            try {
                String expression = bufferedReader.readLine();

                String res = Result.isBalanced(expression);

                bufferedWriter.write(res);
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

제출한 소스코드

 

lemondkel - Overview

4-Year Web programmer. lemondkel has 41 repositories available. Follow their code on GitHub.

github.com

 

반응형