TheAlgorithms-C-Plus-Plus/others/paranthesis_matching.cpp

88 lines
1.7 KiB
C++
Raw Normal View History

2020-05-28 23:24:46 +08:00
/**
* @file
* @brief Perform paranthesis matching. \note Do not know the application of
* this, however.
* @note Implementation is C-type and does not utilize the C++ constructs
* @todo implement as a C++ class
*/
2019-08-21 10:10:08 +08:00
#include <iostream>
2020-05-28 23:24:46 +08:00
#ifdef _MSC_VER
#include <string> // Visual Studio C requires this include
#else
#include <cstring>
#endif
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
/** check number */
2018-11-14 01:02:40 +08:00
#define MAX 100
2018-03-28 04:51:40 +08:00
2020-05-28 23:24:46 +08:00
//! @{-------------- stack --------------
//! global stack
2018-03-28 04:51:40 +08:00
char stack[MAX];
2020-05-28 23:24:46 +08:00
//! pointer to track stack index
2018-11-14 01:02:40 +08:00
int top = -1;
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
//! push byte to stack variable
void push(char ch) { stack[++top] = ch; }
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
//! pop a byte out of stack variable
char pop() { return stack[top--]; }
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
//! @}-------------- end stack -----------
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
/** return opening paranthesis corresponding to the close paranthesis
* @param[in] ch closed paranthesis character
*/
char opening(char ch)
{
switch (ch)
{
case '}':
return '{';
case ']':
return '[';
case ')':
return '(';
case '>':
return '<';
2020-05-28 23:24:46 +08:00
}
return '\0';
2018-11-14 01:02:40 +08:00
}
int main()
{
2020-05-28 23:24:46 +08:00
std::string exp;
int valid = 1, i = 0;
std::cout << "Enter The Expression : ";
std::cin >> exp;
2019-08-21 10:10:08 +08:00
while (valid == 1 && i < exp.length())
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<')
{
2020-05-28 23:24:46 +08:00
push(exp[i]);
}
else if (top >= 0 && stack[top] == opening(exp[i]))
{
2020-05-28 23:24:46 +08:00
pop();
}
else
{
2020-05-28 23:24:46 +08:00
valid = 0;
}
i++;
}
2017-12-24 01:30:49 +08:00
2020-05-28 23:24:46 +08:00
// makes sure the stack is empty after processsing (above)
if (valid == 1 && top == -1)
{
2020-05-28 23:24:46 +08:00
std::cout << "\nCorrect Expression";
}
else
{
2020-05-28 23:24:46 +08:00
std::cout << "\nWrong Expression";
}
2018-03-28 04:51:40 +08:00
2020-05-28 23:24:46 +08:00
return 0;
2017-12-24 01:30:49 +08:00
}