14379: 【原4379】字符串匹配
题目
题目描述
author: 黄江林 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/4379
Description
给定一个字符串s,只包括'(',')','[',']','{','}'这些字符,判断该字符串是否有效,即左括号必须使用同类型的右括号闭合并且以正确的顺序闭合。
Input Format
输入 第一行:一个字符串
Output Format
输出 第一行:1/0
Sample Input
"({)}"
Sample Output
0
Sample Input
"([{}])"
Sample Output
1
Limits
1 <= s.length() <= 10000
ligongzzz's solution
//
// Created by 谢哲 on 2021/4/22.
//
// 注意:这道题的输入不包括两侧的双引号
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
stack<char> sdata;
if (s.length()<1 || s.length()>10000) {
cout << 0;
return 0;
}
for (auto p: s) {
if (p==')') {
if (sdata.empty()||sdata.top()!='(') {
cout<<0;
return 0;
}
else sdata.pop();
}
else if (p==']') {
if (sdata.empty()||sdata.top()!='[') {
cout<<0;
return 0;
}
else sdata.pop();
}
else if (p=='}') {
if (sdata.empty()||sdata.top()!='{') {
cout<<0;
return 0;
}
else sdata.pop();
}
else sdata.push(p);
}
if (sdata.empty()) {cout<<1;}
else cout<<0;
return 0;
}