Coding Test/HackerRank

[HackerRank] Balanced Brackets c++

owls 2023. 5. 15. 22:13
728x90
  • Problem
 

Balanced Brackets | HackerRank

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

www.hackerrank.com

  • Solutions

stack을 사용하는 대표적인 문제 유형이다.

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

string isBalanced(string s) {
    string result("");
    
    stack<char> st;
    map<char, char> hash;
    hash['('] = ')';
    hash['{'] = '}';
    hash['['] = ']';
    for(const auto& c : s){
        if('(' == c || '{' == c || '[' == c ){
            st.push(c);
        }
        else{
            if(st.empty()){
                return "NO";
            }
            if(hash[st.top()] == c){
                st.pop();
            }
            else{
                return "NO";
            }
        }
    }
    
    result = st.empty() ? "YES" : "NO";
    
    return result;
}

 

728x90