Sort by

recency

|

1628 Discussions

|

  • + 0 comments
    def isBalanced(s):
        closeToOpen = { ")" : "(", "]" : "[", "}" : "{" }
        Stack = []
    
        for x in s:
            if x in closeToOpen:
                if Stack and Stack[-1] == closeToOpen[x]:
                    Stack.pop()
                else:
                    return "NO"
            else:
                Stack.append(x)
    
        return "NO" if len(Stack) > 0 else "YES"
    
  • + 0 comments

    C++:

    string isBalanced(string s) { std::map m {{'(',')'}, {'{','}'}, {'[',']'}}; std::stack st;

    if (s.length() %2 != 0)
        return("NO");
    for (int i=0;i<s.length();i++)
    {
        auto it = m.find(s[i]);
        if(it != m.end())
        {
            st.push(s[i]);
        }
        else
        {
            if(st.empty())
            {
                return("NO");
            }
            if(m[st.top()] == s[i])
                st.pop();
            else
                return("NO");
        }
    }
    if(st.empty())
        return("YES");
    else    
        return("NO");
    

    }

  • + 0 comments

    Simple java solution in O(n) 100%:

    public static String isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> dict = Map.of('{','}', '[',']', '(',')');
    
        for (char c : s.toCharArray()) {
            if (dict.containsKey(c)) stack.push(dict.get(c));
            else if (stack.isEmpty() || c != stack.pop()) return "NO";
        }
    
        return stack.isEmpty() ? "YES" : "NO";
    }
    
  • + 0 comments

    Python 3:

    Write your code here

    stack = []
    pairs = {
        '[': ']',
        '{': '}',
        '(': ')'
    }
    
    for bracket in s:
        if bracket in pairs:
            stack.append(bracket)
        elif not stack or pairs.get(stack.pop(-1)) != bracket:
            return 'NO'
    
    return 'YES' if not stack else 'NO'
    
  • + 0 comments

    Python3

    def isBalanced(s):
        # Valid combos that must exist as pairs
        combos = ["[]", "{}", "()"]
        
        # While there are characters available, attempt to remove combos
        while len(s) > 0:
            new_s = s
            for c in combos:
                new_s = new_s.replace(c, "")
            # If the new_s has not changed length (ie no valid combos) return NO
            if len(new_s) == len(s):
                return "NO"
            s = new_s
        return "YES"