Search code examples
c#stringwhile-loopcharstack

How to make a function that checks the validity of brackets in a string?


I have coded a function that check if brackets in a certain string are valid and returns true if it is and false if it isn't.

For example:

str1: { [ a + b ] - ] ( c - d } ] = false.

str2: { [ a + b ] - ( c - d ) } = true.

When I run the program it doesn't give any output, just a blank output.

What do I need to change?

public static Boolean BracketCheck(string str)
{
    Stack<char> stk = new Stack<char>();
    Stack<char> aid = new Stack<char>();
    Stack<char> temp = new Stack<char>();
    while (str != "")
    {
        char ch = str[0];
        if(ch == '(' || ch == '{' || ch == '[' || ch == ')' || ch == '}' || ch == ']')
        {
            stk.Push(ch);
        }
        if(str.Length != 1)
            str = str.Substring(1, str.Length - 1);
    }
    stk = Opposite(stk);
    char first = stk.Pop();
    char last;
    while (!stk.IsEmpty() && !aid.IsEmpty())
    {
        while (!stk.IsEmpty())
        {
            aid.Push(stk.Top());
            last = stk.Pop();
            if (stk.IsEmpty())
                if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first + "") + 2 != int.Parse(last + ""))
                {
                    return false;
                }
        }
        first = aid.Pop();
        while (!aid.IsEmpty())
        {
            aid.Push(aid.Top());
            last = aid.Pop();
            if (aid.IsEmpty())
                if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first +  "") + 2 != int.Parse(last + ""))
            {
                return false;
            }
        }
        first = stk.Pop();

    }
    return true;
}
public static Stack<char> Opposite(Stack<char> stk)
{
    Stack<char> temp = new Stack<char>();
    while (stk.IsEmpty())
    {
        temp.Push(stk.Pop());
    }
    return temp;
}

Solution

  • this works for me do you see any issuse or points to improve on?

    public static Boolean BracketCheck(string str)
        {
            Stack<char> stk = new Stack<char>();
            foreach(char c in str)
            {
                if (c == '(' || c == '[' || c == '{')
                {
                    stk.Push(c);
                }
                else if (c == ')' || c == ']' || c == '}')
                {
                    if (stk.Top() == (int)c - 1 || stk.Top() == (int)c - 2)
                    {
                        stk.Pop();
                    }
                }
                
            }
            return stk.IsEmpty();
        }