본문 바로가기
Programming/Data Structure

[Hackerrank] BalancedBrackets

by 읽고 쓰는 개발자 2020. 12. 2.

https://www.hackerrank.com/challenges/balanced-brackets/problem

 

Arrays - DS | HackerRank

Accessing and using arrays.

www.hackerrank.com

package exam.complete;
//https://www.hackerrank.com/challenges/balanced-brackets/problem


import java.util.Stack;

public class BalancedBrackets {
    static String isBalanced(String s) {
        String answer = "NO";
        Stack<Character> stack = new Stack<>();

        char[] array = s.toCharArray();
        for (char i : array) {
            if (i == '(' || i == '{' || i == '[') stack.push(i);
            else {
                if(stack.empty()) return answer;
                Character nowChar = stack.pop();
                if(!((i == '}' && nowChar == '{') || (i == ']' && nowChar == '[') || (i == ')' && nowChar == '('))) return answer;
            }
        }
        return stack.empty() ? "YES" : answer;
    }
}

 

'Programming > Data Structure' 카테고리의 다른 글

[Hackerrank] DeleteNode  (0) 2020.12.02
[Hackerrank] CompareTwoLinkedLists  (0) 2020.12.02
[Hackerrank] reverseArray  (0) 2020.12.02
[Hackerrank] MaximumElement  (0) 2020.12.02
[Hackerrank] hourglassSum  (0) 2020.12.02