Skip to content

Commit 4df93bc

Browse files
committed
Valid Parentheses
1 parent a09b177 commit 4df93bc

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Stack/ValidParentheses.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

Stack/ValidParentheses.exe

79.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)