-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid.cpp
More file actions
37 lines (32 loc) · 904 Bytes
/
Valid.cpp
File metadata and controls
37 lines (32 loc) · 904 Bytes
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
#include <iostream>
using namespace std;
bool isValid(string s) {
char stack[1000]; // array stack
int top = -1; // stack pointer
for (int i = 0; i < s.length(); i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
stack[++top] = c; // push opening bracket
}
else {
if (top == -1) return false; // no matching opening
char last = stack[top--]; // pop
if ((c == ')' && last != '(') ||
(c == '}' && last != '{') ||
(c == ']' && last != '[')) {
return false; // wrong match
}
}
}
return (top == -1); // stack should be empty at end
}
int main() {
string s;
cout << "Enter string: ";
cin >> s;
if (isValid(s))
cout << "true\n";
else
cout << "false\n";
return 0;
}