Please write a program to check whether the following symbols in the C language source program are matched: /* and */, (and), [and], {and}.
Input format:
input is a C language source program. When there is only one period. and one carriage return in a certain line, it marks the end of input. There are no more than 100 symbols that need to be checked in the program.
Output format:
First, if all symbols are paired correctly, output YES in the first line, otherwise output NO. Then point out the first unpaired symbol in the second line: if the left symbol is missing, output ?-right symbol; if the right symbol is missing, output left symbol -?.
Question idea: Seeing the problem of symbol matching, directly considering the use of the stack to solve it, you can use the <stack> template in C++, (if you don't understand the STACK template, you can go and learn by yourself). Upload the code.
#include<iostream>
#include<stack>
using namespace std;
char t;
stack<char> st;
bool deal(stack<char>& st); //注意,这里一定需要‘&’,否则在main里st是没有元素的
int main()
{
if (deal(st))
cout << "YES" << endl;
else
{
if (st.empty())
{
switch (t)
{
case ')':cout << "NO\n?-)" << endl; break;
case ']':cout << "NO\n?-]" << endl; break;
case '}':cout << "NO\n?-}" << endl; break;
case'*':cout << "NO\n?-*/" << endl; break;
}
}
else
{
switch (st.top())
{
case '(': cout << "NO\n(-?" << endl; break;
case '{': cout << "NO\n{-?" << endl; break;
case '[': cout << "NO\n[-?" << endl; break;
case '*': cout << "NO\n/*-?" << endl; break;
}
}
}
return 0;
}
bool deal(stack<char>& st)
{
char c[101];
bool flag = true;
while (cin >> c)
{
if (c[0] == '.' && c[1] == '\0') break;
for (int i = 0; c[i] != '\0'; i++)
{
if (c[i] == '/' && c[i + 1] == '*')
{
st.push(c[i]);
st.push(c[i + 1]);
i++;
}
else if (c[i] == '{' || c[i] == '[' || c[i] == '(')
st.push(c[i]);
else if (c[i] == '*' && c[i + 1] == '/')
{
if (!st.empty() && st.top() == '*')
{
st.pop();
if (!st.empty() && st.top() == '/')
st.pop();
else
{
flag = false;
t = c[i];
break;
}
}
else
{
flag = false;
t = c[i];
break;
}
}
else if (c[i] == ')')
{
if (!st.empty() && st.top() == '(')
st.pop();
else
{
flag = false;
t = c[i];
break;
}
}
else if (c[i] == '}')
{
if (!st.empty() && st.top() == '{')
st.pop();
else
{
flag = false;
t = c[i];
break;
}
}
else if (c[i] == ']')
{
if (!st.empty() && st.top() == '[')
st.pop();
else
{
flag = false;
t = c[i];
break;
}
}
}
}
if (st.empty() && flag)
return true;
else
return false;
}