-
Notifications
You must be signed in to change notification settings - Fork 2
/
38_bracket_problem.cpp
77 lines (73 loc) · 1.53 KB
/
38_bracket_problem.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <stack>
#include <string>
bool isMatched(char begin, char end)
{
return (begin == '(' && end == ')') ||
(begin == '{' && end == '}') ||
(begin == '[' && end == ']');
}
bool isBalanced(std::string s)
{
std::stack<char> stck;
for (char c : s)
{
switch (c)
{
case '(':
case '{':
case '[':
stck.push(c);
break;
case ']':
case '}':
case ')':
if (stck.empty() || !isMatched(stck.top(), c))
{
return false;
}
stck.pop();
break;
}
}
return stck.empty();
}
int main()
{
std::string s = "{[]}()[]";
// 1st implementation
std::stack<char> stck;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '{' || s[i] == '(' || s[i] == '[')
{
stck.push(s[i]);
}
else
{
if (stck.top() == '[' && s[i] != ']' || stck.top() == '{' && s[i] != '}' || stck.top() == '(' && s[i] != ')')
{
std::cout << "Flase";
return 0;
}
else if (stck.empty())
{
std::cout << "Flase";
return 0;
}
stck.pop();
}
}
if (stck.empty())
{
std::cout << "True";
}
else
{
std::cout << "False";
}
// second implementation
bool isMatch = isBalanced(s);
std::cout << isMatch;
return 0;
}