- #1
fadi_nzr
- 14
- 0
Hello
I am writing the balance function that should figure out whether the left and right parens ( ) , the left and right brackets [ ] , and the left and right curly brackets { } are properly matched and nested in the string arg. For instance,
examples "(sldkj[slkdfjk{slkdfjsl(sldkjf(lkjsd)slkdfj)sldkfj}slkdjf]sldkfj)": balanced,
"(((( [[[[ ]]]]{{{{ }}}} ))))": balanced
"([)]": not balanced (even though we have left & right paren and a left & right bracket)
"": balanced, no parens means no mismatch
I am writing the balance function that should figure out whether the left and right parens ( ) , the left and right brackets [ ] , and the left and right curly brackets { } are properly matched and nested in the string arg. For instance,
examples "(sldkj[slkdfjk{slkdfjsl(sldkjf(lkjsd)slkdfj)sldkfj}slkdjf]sldkfj)": balanced,
"(((( [[[[ ]]]]{{{{ }}}} ))))": balanced
"([)]": not balanced (even though we have left & right paren and a left & right bracket)
"": balanced, no parens means no mismatch
Code:
bool balanced(const string & line)
{
Stack sk;
initialize(sk);
if (line.size() > STACK_SIZE) die("stack overflow");
for (unsigned i = 0; i < line.size(); i++)
{
switch (line[i])
{
case '(':
push(sk, line);
if (line[i] == ')')
{
if (top(sk)== "(") return 0;
else pop(sk);
}
case '[':
push(sk, line);
if (line[i] == ']')
{
if (top(sk) == "[") return 0;
else pop(sk);
}
case'{':
push(sk, line);
if (line[i] == '}')
{
if (top(sk) == "{") return 0;
else pop(sk);
}
default:
;
}//switch
}//for
if (elements(sk) == 0) return 1;
else return 0;
}//balanced