English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Describe in English without writing any code how you would check a string to ensure that parentheses appearing in that string are balanced.

2006-10-25 06:59:07 · 7 answers · asked by dil k 1 in Computers & Internet Programming & Design

7 answers

Check the string to ensure that pairs of parentheses appear in balance.

That is all that should be required to describe the requirements of a program.

2006-10-25 07:02:39 · answer #1 · answered by Anonymous · 1 0

Check each character and loop though until the end of the string.
First, find the "(" and save the position in the string
then find the ")" in the string and save that position.

If you found only one, it's not balanced

If you found both, the position of the left one must be less than the position of than the right one for it to be balanced.

Otherwise it is not balanced

2006-10-25 14:14:25 · answer #2 · answered by Anonymous · 0 0

Parse the string one character at a time, counting the number of opening and closing parentheses as you go. If the numbers match, the string is balanced.

Rawlyn.

p.s. Homework? lol

2006-10-25 14:12:15 · answer #3 · answered by Anonymous · 0 0

Create a variable of type integer and initialize to zero.

Iterate through each character of your string and increment your variable when you encounter an open parenthesis, and decrement when you encounter a close parenthesis.

When you have completed the iteration, if the variable is zero, then the parentheses are balances, otherwise they are not balanced.

2006-10-25 14:06:31 · answer #4 · answered by dsr 2 · 1 0

I am sure you will get a better response than this, but here we go.

Set count to zero.

Loop
Look at next letter of string
If it is left parenthesis add one to count
If it is right parenthesis take one away from count
If it is the end of string exit the loop
Do loop again

If the count not equal to zero, the parentheses don't match.

2006-10-25 14:03:26 · answer #5 · answered by langdonrjones 4 · 1 0

The method described by dsr and Rawlyn is essentially correct, but I'd also check that the number never goes negative, as that would indicate a parenthesis closing without one being open. It might be "balanced" by one opening later on, but it's syntactically incorrect.

2006-10-25 15:26:46 · answer #6 · answered by injanier 7 · 0 0

I'd find the left-most paren and match it with the right most paren, working my way in until all pairs have been matched. If I have a paren left over, I'd know that they were unbalanced. If not, they're balanced.

(Count parens and divide by two?)

2006-10-25 14:02:54 · answer #7 · answered by Anonymous · 0 1

fedest.com, questions and answers