-3

I want this program to recursively solve this using a stack implementation with push and pop. I have the push and pop done, as well as these functions:

A string the users enter can only be made up of these characters. Any other characters and it returns unbalanced.

'(', ')', '{', '}', '[', ']'

An example of a balanced string is like this

()
(())
()()
{()()}
[]
[()[]{}]()
etc..

An unbalanced string looks like this:

{}}
()[}
[()}
etc..

This is the recursive definition of a balanced string:

  1. (BASIS)The empty string is balanced
  2. (NESTING) If s is also a balanced string then (s), [s], and {s} is balanced.
  3. (CONCATENATION) If A and B are both strings, then AB is also balanced.

I do not know what my base case would be or how to implement this in recursion. I can without but I want to learn recursion. Any help?

code
  • 69
  • 1
  • 9
  • 3
    Don't listen to Andy. You need one stack, and no recursion. You say that you've already done push() and pop(), but they're not here. Without that, we really can't tell you if you're on the right track. – Lee Daniel Crocker Apr 06 '15 at 20:56
  • I didn't post a solution, but rest assured that if I did it would do no such thing. As I said, only one stack is needed, and no recursion is needed. But I don't even see what his stack is storing here, so I can't comment on OP. – Lee Daniel Crocker Apr 06 '15 at 20:59
  • AndyG's general idea is correct though. When you encounter an opening scope, you push onto the stack. When you encounter a closing scope, you pop. Any errors or excess tokens indicates a lack of balance. –  Apr 06 '15 at 21:01
  • @code - to offer a bit more detail, there certainly is a solution that uses recursion, but it will not involve a stack. The stack essentially provides what you would get out of recursion. So you can either have a stack solution or a recursive solution, but wouldn't make sense to have a recursive solution that tries to use a stack. – akira Apr 06 '15 at 21:01
  • @LeeDanielCrocker I updated it with the stack.c and stack.h – code Apr 06 '15 at 21:05
  • if you want to do it non recursively, you need a stack. If you want to do it recursively, you don't need a stack ( the recursion is effectively a stack ) – Keith Nicholas Apr 06 '15 at 21:23
  • @KeithNicholas can you explain how recursion is a stack? Thanks – code Apr 06 '15 at 22:34
  • @code, function calls in C use the processor stack, it pushes all its parameters and local variables on to the system stack ( managed by the CPU). So every function call nests onto this stack. – Keith Nicholas Apr 06 '15 at 22:42
  • @code You marked as the best the wrong solution because it does not uses a stack. Moreover it is a bad solution because a simple recursive function is split into two functions. There is no any need to do such a splitting. The obky full and correct solution is the solution I showed.:) Good luck! – Vlad from Moscow Apr 07 '15 at 05:15
  • Thats not what i meant to best my bad. It's this phone – code Apr 07 '15 at 05:16

4 Answers4

0

I think you want to implement "Parenthesis Balanced" problem. You can solve it easily by using stack without any recursion operation. You can follow this.

//stk is a stack
// s is a string
for(int i=0; i<s.size(); i++)
{
   if(str[i]=='('||str[i]=='[')
      stk.push(s[i]);
   else if(str[i]==')' && !stk.empty() && stk.top()=='(')
      stk.pop();
   else if(str[i]==']' && !stk.empty() && stk.top()=='[')
      stk.pop();
}

Then by using a flag you can find this string of parenthesis is balanced or not. You can get help from this question. Same to your question(Basic Recursion, Check Balanced Parenthesis) I think.

Community
  • 1
  • 1
Mr. Perfectionist
  • 2,605
  • 2
  • 24
  • 35
  • What is a flag? Also I would need to recursively call this right? – code Apr 06 '15 at 21:07
  • 1
    Nope, that code is almost complete (needs to add {} and a few checks). As akira says above, if you have an explicit stack, no recursion needed. Recursion is just using the system's implicit stack. – Lee Daniel Crocker Apr 06 '15 at 21:08
  • 1
    No friend. I think you don't know about recursion. You just have to take a string and then write this code. At last, you have to check stack is empty or not. If empty then it is balanced. – Mr. Perfectionist Apr 06 '15 at 21:12
-1

Well, having double as your stack's element type is rather wasteful, but I'll play along:

int is_balanced(char *ins) {
    SPointer st = stk_create(),
    int rval = 1;

    for (int i = 0; i < strlen(ins); i += 1) {
        int c = ins[i];

        if ('(' == c) stk_push(st, (ElemType)')');
        else if ('[' == c) stk_push(st, (ElemType)']');
        else if ('{' == c) stk_push(st, (ElemType)'}');
        else if (')' == c || ']' == c || '}' == c) {
            if (stk_empty(st) || c != stk_pop(st)) {
                rval = 0;
                break;
            }
        } else {
            rval = 0;
            break;
        }
    }
    if (! stk_empty(st)) rval = 0;

    stk_free(st);
    return rval;
}
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
-1

Recursively done...

char* balanced_r(char* s, int* r)
{
    const char* brackets= "([{\0)]}";
    char *b = brackets;
    if (s == 0) return s;
    if (*s == 0) return s;
    while (*b && *b != *s) b++;
    if (*s == *b)
    {
        s = balanced_r(s+1, r);
        if (*s != *(b+4)) *r = 0;       
        return balanced_r(s + 1, r);
    }   
    return s;
}


int balanced(char* s)
{
    int r = 1;
    balanced_r(s, &r);
    return r;
}
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
-2

Here is a demonstrative program written in C++ that you can use as an algorithm and rewrite it in C

#include <iostream>
#include <iomanip>
#include <stack>
#include <cstring>

bool balance( const char *s, std::stack<char> &st )
{
    const char *open  = "({[<";
    const char *close = ")}]>";

    if ( *s == '\0' )
    {
        return st.empty();
    }

    const char *p;

    if ( ( p = std::strchr( open, *s ) ) != nullptr )
    {
        st.push( *s );
        return balance( s + 1, st );
    }
    else if ( ( p = std::strchr( close, *s ) ) != nullptr )
    {
        if ( !st.empty() && st.top() == open[p-close] )
        {
            st.pop();
            return balance( s + 1, st );
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}   

int main() 
{

    for ( const char *s : { 
                            "()", "(())", "()()", "{()()}", "[]", "[()[]{}]()",
                            "{}}", "()[}", "[()}"

                          } )
    {
        std::stack<char> st;

        std::cout <<'\"' << s << "\" is balanced - "
                  << std::boolalpha << balance( s, st )
                  << std::endl;
    }


    return 0;
}

The program output is

"()" is balanced - true
"(())" is balanced - true
"()()" is balanced - true
"{()()}" is balanced - true
"[]" is balanced - true
"[()[]{}]()" is balanced - true
"{}}" is balanced - false
"()[}" is balanced - false
"[()}" is balanced - false
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335