forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid_parenthesis.cpp
47 lines (44 loc) · 1.21 KB
/
valid_parenthesis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* Given a string containing just the characters '(', ')', '{', '}',
* '[' and ']', determine if the input string is valid. The brackets must
* close in the correct order, "()" and "()[]{}"
* are all valid but "(]" and "([)]" are not.
*/
#include <iostream>
#include <stack>
bool is_valid_parenthesis(std::string str)
{
std::stack<char> st;
for (char c: str) {
if (c == '(') {
st.push(')');
} else if (c == '{') {
st.push('}');
} else if (c == '[') {
st.push(']');
} else if (!st.empty()) {
if (st.top() != c) {
return false;
} else {
st.pop();
}
}
}
return st.empty();
}
int main()
{
std::string str1{"()[]{}"};
if (is_valid_parenthesis(str1)) {
std::cout << str1 << " has valid parenthesis." << std::endl;
} else {
std::cout << str1 << " does not have valid parenthesis." << std::endl;
}
std::string str2{"([)]"};
if (is_valid_parenthesis(str2)) {
std::cout << str2 << " has valid parenthesis." << std::endl;
} else {
std::cout << str2 << " does not have valid parenthesis." << std::endl;
}
return 0;
}