括號匹配檢測(難度:半顆星)
阿新 • • 發佈:2018-12-21
問題描述:
輸入一個字串,字串中只包含兩種字元:’(‘和’)’,判斷字串的括號是否匹配,如果匹配輸出YES,否則輸出NO。
例如:
(())是匹配的
()))是不匹配的
參考程式碼:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stack>
std::stack<char>st;
int main()
{
char str[500];
int i;
scanf("%s", str);
for (i = 0; i < (int)strlen(str); i++)
{
if (str[i] == '(')
st.push(str[i]);
else
{
if (st.empty())
{
printf("NO\n");
return 0;
}
st.pop();
}
}
if (st.empty())
printf ("YES\n");
return 0;
}
執行結果: