-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbalancedParens.cpp
55 lines (47 loc) · 1.46 KB
/
balancedParens.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
#include <iostream>
#include <stack>
#include <string>
bool is_balanced(const std::string &str) {
std::stack<char> stack;
for (char c : str) {
switch (c) {
case '(':
stack.push(c);
break;
case ')':
// Don't pop from empty stack
if (stack.empty()) return false;
stack.pop();
break;
}
}
return stack.size() == 0;
}
bool is_balanced2(const std::string &str) {
std::string::size_type i = 0;
for (char c : str) {
switch (c) {
case '(':
++i;
break;
case ')':
// Don't underflow
if (i == 0) return false;
--i;
break;
}
}
return i == 0;
}
int main() {
std::cout << "Testing is_balanced:\n";
std::cout << "Is '()' balanced?: " << (is_balanced("()") ? "true" : "false") << std::endl;
std::cout << "Is '(()' balanced?: " << (is_balanced("(()") ? "true" : "false") << std::endl;
std::cout << "Is '((test))' balanced?: " << (is_balanced("(())") ? "true" : "false") << std::endl;
std::cout << "Is '(()))' balanced?: " << (is_balanced("(()))") ? "true" : "false") << std::endl;
std::cout << "\nTesting is_balanced2:\n";
std::cout << "Is '()' balanced?: " << (is_balanced2("()") ? "true" : "false") << std::endl;
std::cout << "Is '(()' balanced?: " << (is_balanced2("(()") ? "true" : "false") << std::endl;
std::cout << "Is '((test))' balanced?: " << (is_balanced2("(())") ? "true" : "false") << std::endl;
std::cout << "Is '(()))' balanced?: " << (is_balanced2("(()))") ? "true" : "false") << std::endl;
}