r/dailyprogrammer_ideas • u/TheMsDosNerd • Aug 17 '19
[easy] Are all brackets matching?
Given a piece of text, discover whether all opening brackets have a corresponding closing bracket after it.
- There are 4 types of brackets: (, [, { and <. Each of these opening brackets must be closed by the corresponding closing bracket: ), ], } and >.
- Each closing bracket must have a corresponding opening bracket in front of it.
- If an opening bracket A comes before opening bracket B, B must be closed before A.
- All text that are not brackets, can be ignored.
Input description
A string.
Output description
A boolean, which is true if all requirements above are satisfied.
Examples:
"This is a text without brackets" --> True
"()[]{}<>" --> True
"not clo(sed" --> False
"[s(o{m(e( <w>o)r)d}s)!]" --> True
"Closed}be4{opened" --> False
"[<]>" --> False
8
Upvotes
4
u/Philboyd_Studge Aug 17 '19
Since it's an "easy" one, you might want to hint at or link to the use of a Stack to solve.
1
u/MightyD33r Jan 14 '20
`def validBraces(string):
2
u/tomekanco Aug 26 '19 edited Aug 26 '19
Yes, that's a classic one.
Here is a good SO post on the subject. And here are some more details if you want to get into performance.
A a bonus, you could throw in a variation on evaluate a math expression, thought that's a bit standard. There was already the [reverse polish notation problem] (https://www.reddit.com/r/dailyprogrammer/comments/2yquvm/20150311_challenge_205_intermediate_rpn/) (good old HP hand calculators for the win).
An alternative would be this brace expansion problem. Not die-hard, but usefull in real life problems.
1
u/-ftw Aug 17 '19
You can find this problem on leetcode