Matching Brackets
Limits 1s, 512 MB
You will be given a sequence of opening and closing brackets of different types (
(
, )
, [
, ]
, {
, and }
). You will have to determine if the sequence is a valid one.
A sequence of brackets is considered valid if every opened bracket of a type has a closing bracket of an equivalent type appearing after it. And, there are no unpaired brackets in the sequence.
Input
The input will contain a string of opening and closing brackets. The string will be no longer than 25 characters.
Output
Print “Yes” if the input string contains a valid sequence of parentheses. Otherwise, print “No”.
Samples
Input | Output |
---|---|
[[(){]}] | No |
Input | Output |
---|---|
(([]{}[{}]){})[] | Yes |
#include <bits/stdc++.h> using namespace std; int main() { string s; stack<char> a; cin>>s; for(int i=0;i<s.length();i++) { if(s[i] == '(' || s[i] == '{' || s[i] == '[') a.push(s[i]); else { if(a.empty()) { cout<<"No"<<endl; return 0; } else if(s[i] == ')') { if(a.top() == '(') { a.pop(); } } else if(s[i] == '}') { if(a.top() == '{') { a.pop(); } } else if(s[i] == ']') { if(a.top() == '[') { a.pop(); } } } } if(a.empty()) { cout<<"Yes"<<endl; return 0; } else cout<<"No"<<endl; }
1 Comments
is there any solution in c?
ReplyDelete