Написал код C ++, чтобы проверить, имеет ли выражение сбалансированные скобки и мой код не работает. Я застрял на один день - PullRequest
1 голос
/ 01 февраля 2020

Код указан ниже. Нет синтаксической ошибки, и код, используемый для безупречной работы, если я проверил соответствие для круглых скобок only (), но после того, как я добавил несколько операторов if .. else .. для проверки соответствия для других скобок, мой код сломался. Я не могу понять свою ошибку. Пожалуйста помоги!! Я думаю, что сделал глупую ошибку, но не могу понять, что.

// structure of a stack

struct stackStructure
{
    // top pointer of the stack
    int top;
    // pointer to the array/stack
    char *array;
}stack;

// function to push element to stack

void push(char data)
{
    if(stack.top == 999)
    {
        cout<<"Stack Overflow"<<endl;
        return;
    }
    else
    {
        // incrementing the top and then pushing data to the stack
        stack.top++;
        stack.array[stack.top]= data;
    }
} // end of push() function

// function to pop elements from the stack

char pop()
{
    if(stack.top == -1)
        return '\0';
    else
        // returning the popped value and then decrementing the top pointer
        return stack.array[stack.top--];
} // end of pop() function
int main()
{
    // match variable to keep track that closing bracket and opening brackets are in sequence
    char match= '\0';
    bool isMatching= true;
    // resetting the stack variables and attributes
    stack.top= -1;
    stack.array= new char[1000];
    cout<<"Enter the Expression to match the parenthesis: ";
    cin>>stack.array;

    // traversing through the character array and matching parenthesis
    for(int i=0; stack.array[i] != NULL; i++)
    {
        // if character is an opening bracket
        if(stack.array[i] == '(' || stack.array[i] == '{' || stack.array[i] == '[')
            push(stack.array[i]);
        // if character is a closing bracket
        else if(stack.array[i] == ')' || stack.array[i] == '}' || stack.array[i] == ']')
        {
            match= pop();
            if(stack.array[i] != match)
                isMatching= false;
        }
        // if character is anything else we do nothing
        else
            continue;
    }
    if(isMatching == true)
        cout<<"Parenthesis Matched"<<endl;
    else
        cout<<"Not matched"<<endl;
    return 0;
}

1 Ответ

1 голос
/ 01 февраля 2020

У вас 2 ошибки. Во-первых, чтение вашей входной строки в ваш стек, как минимум, это будет очень запутанным и в худшем случае не сработает.

Во-вторых, при проверке совпадения тегов вы проверяете, совпадает ли открывающая скобка с закрывающий, это никогда не будет правдой, вам нужно проверить, что открывающая скобка имеет тот же тип, что и закрывающая.

Один из способов устранения обеих ошибок:

int main()
{
    // match variable to keep track that closing bracket and opening brackets are in sequence
    char match = '\0';
    bool isMatching = true;
    // resetting the stack variables and attributes
    stack.top = -1;
    stack.array = new char[1000];
    std::string input;
    cout << "Enter the Expression to match the parenthesis: ";
    cin >> input;

    std::map<char, char> opening = { { ')', '(' }, { '}', '{' }, { ']', '[' } };

    // traversing through the character array and matching parenthesis
    for (char ch : input)
    {
        // if character is an opening bracket
        if (ch == '(' || ch == '{' || ch == '[')
            push(ch);
        // if character is a closing bracket
        else if (ch == ')' || ch == '}' || ch == ']')
        {
            match = pop();
            auto open = opening.find(ch);
            if (open == opening.end() || open->second != match )
                isMatching = false;
        }
    }
    if (isMatching == true)
        cout << "Parenthesis Matched" << endl;
    else
        cout << "Not matched" << endl;
    delete[] stack.array;
    return 0;
}
...