We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Practice
  • Certification
  • Compete
  • Career Fair
  • Hiring developers?
  1. Practice
  2. Tutorials
  3. Cracking the Coding Interview
  4. Stacks: Balanced Brackets
  5. Discussions

Stacks: Balanced Brackets

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 408 Discussions, By:

votes

Please Login in order to post a comment

  • dgodfrey 4 years ago+ 0 comments

    After writing several bad programs that barely passed the test cases, I was able to come up with this cool solution:

    bool is_balanced(string expression) {
      stack<char> s;
      for (char c : expression) {
        if      (c == '{') s.push('}');
        else if (c == '[') s.push(']');
        else if (c == '(') s.push(')');
        else {
          if (s.empty() || c != s.top())
            return false;
          s.pop();
        }
      }
      return s.empty();
    }
    
    178|
    Permalink
  • stomatrix 4 years ago+ 0 comments

    here's my pythonic solution

    def is_matched(e):
        while( len(e) > 0):
            t = e
            e = e.replace('()','')
            e = e.replace('{}','')
            e = e.replace('[]','')
            if t == e:
        		return False
            
        return True
    
    27|
    Permalink
  • nevertoolate 4 years ago+ 0 comments

    I initially misunderstand the problem. I thought you don't really need a stack. Just traverse the string in lock step from both ends. Return false when there is a mismatch. But looking at the failing tests I realized that the example and the explanation of the problem is incomplete.

    23|
    Permalink
  • by424 4 years ago+ 0 comments

    Python solution using stack principle:

    def is_matched(expression):
        dic = {'{':'}','[':']','(':')'}
        lst =[]
        for i in expression:
            if i in dic.keys():
                lst.append(dic[i])
            elif len(lst)>0 and i==lst[-1]:
                lst.pop()
            else: 
                return False
        return len(lst) == 0
    
    13|
    Permalink
  • marcin_tustin 4 years ago+ 0 comments

    Poor examples. For example, this is a case not alluded to in the description:

    }][}}(}][))] => No {()} => Yes () => Yes ({}([][])) => Yes {))}(())(

    10|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature