Check if the parentheses (), square brackets [] and curly brackets {} of a piece of C language code match.
Input format:
Enter a section of C language code in one line, the length does not exceed 1000 characters (the line ends with a newline character).
Output format: The
first line outputs the number of left parentheses and the number of right parentheses, separated by a space.
If the brackets match, print YES on the second line, otherwise print NO.
Input example 1:
for(int i=0; i<v; i++){
visited[i] = 0; for(int j=0; j<v; j++) scanf("%d",&(g->Adj[i][j])); }
Output example 1:
8 8
YES
Input example 2:
for(int i=0; i<v; i++) a(i]=0;
Output example 2:
2 2
NO
At the beginning, it has been 16 points/14 points. The reason is the YES and NO problems. It is necessary to ensure that flag and cnt1=cnt2. If cnt2 = 0, then flag=true, which is equivalent to output YES in the end, which is obviously wrong.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
int cnt1 = 0, cnt2 = 0;
stack<char> st;
bool flag = true;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push(s[i]);
cnt1++;
} else if (s[i] == ')') {
cnt2++;
if (!st.empty() && st.top() == '(')
st.pop();
else
flag = false;
} else if (s[i] == ']') {
cnt2++;
if (!st.empty() && st.top() == '[')
st.pop();
else
flag = false;
} else if (s[i] == '}') {
cnt2++;
if (!st.empty() && st.top() == '{')
st.pop();
else
flag = false;
}
}
cout << cnt1 << " " << cnt2 << endl;
if (flag && cnt1 == cnt2)
cout << "YES";
else
cout << "NO";
return 0;
}