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.
Stacks: Balanced Brackets
Stacks: Balanced Brackets
dgodfrey + 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(); }
stomatrix + 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
nevertoolate + 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.
by424 + 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
marcin_tustin + 0 comments Poor examples. For example, this is a case not alluded to in the description:
}][}}(}][))] => No {()} => Yes () => Yes ({}([][])) => Yes {))}(())(
Load more conversations
Sort 408 Discussions, By:
Please Login in order to post a comment