A stack can be used to check whether opening and closing brackets: '(' and ')', '[' and ']', '{' and '}', are balanced in given text. For example, the following are all balanced:
void f(char a[], int n) {int i; for(i=0;i<n;i++) a[i] = (a[i]*a[i]*a[i])*(i+1); return;}
|
([{}]) ([{}]) ([{}]) ([{}]) ([{}]) ([{}])
|
((())){{[]}{()()()}}(()){{}}
|
Examples of text that is not balanced:
((())){{[]}{(()()}}(()){{}}
|
Sketch an algorithm that uses a stack to determine whether given text contained balanced brackets. Consider in particular the following cases, and show how your algorithm works for these:
- mismatched kind of bracket: e.g. (]
- missing opening bracket: e.g. ())
- missing closing bracket: e.g. (()