Skip to main content

Posts

Showing posts from January, 2017

Balanced brackets in C++

It was a question on coursera course in Data structure and I spent some time on the program. Though I had taught the program to students earlier. But somehow coursera is not accepting my submission:( So why not blog it? The question is Write a program to balance brackets using stack. This is fundamental requirement in any programming language. Let us look at some valid and invalid  strings. {[]}()   valid []{}()[] valid {([([])])} valid {}) invalid ([)] invalid ({[]} invalid You are getting the gist, right? When ever there is an opening bracket, there should be a corresponding closing bracket of matching type. And order is important, you can not have round bracket , square bracket followed by closing round bracket first and square bracket next. So the algorithm is very simple create a stack of characters repeat for each i from 0 to length of string ch = ith character if ch is either { or [ or (, push it to stack if ch is closing bracket i.e. } or ] or }  get stack top charcter ch2 if c