File tree 2 files changed +48
-0
lines changed
2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < stack>
3
+ #include < string>
4
+ using namespace std ;
5
+
6
+ bool isValid (string s)
7
+ {
8
+ stack<char > st;
9
+
10
+ for (int i = 0 ; i < s.size (); i++)
11
+ {
12
+ if (s[i] == ' (' || s[i] == ' {' || s[i] == ' [' ) // opening brackets
13
+ {
14
+ st.push (s[i]);
15
+ }
16
+ else // closing bracket
17
+ {
18
+ if (st.size () == 0 ) // stack is empty or no opening brackets
19
+ {
20
+ return false ;
21
+ }
22
+
23
+ if (st.top () == ' (' && s[i] == ' )' ||
24
+ st.top () == ' {' && s[i] == ' }' ||
25
+ st.top () == ' [' && s[i] == ' ]' )
26
+ { // match found
27
+ st.pop ();
28
+ }
29
+ else // no match found
30
+ {
31
+ return false ;
32
+ }
33
+ }
34
+ }
35
+
36
+ return st.size () == 0 ;
37
+ }
38
+
39
+ int main ()
40
+ {
41
+ string s1 = " ()[]{}" ;
42
+ string s2 = " (]" ;
43
+
44
+ cout << isValid (s1) << endl;
45
+ cout << isValid (s2) << endl;
46
+
47
+ return 0 ;
48
+ }
You can’t perform that action at this time.
0 commit comments