-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimized.cpp
More file actions
46 lines (42 loc) · 1.49 KB
/
Copy pathoptimized.cpp
File metadata and controls
46 lines (42 loc) · 1.49 KB
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
#include <stack>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
/*
* Valid Parentheses - Optimized Solution using Stack with Hash Map
*
* Approach:
* - Use a stack to track opening brackets
* - Use a hash map for O(1) bracket matching lookup
* - For opening brackets: push to stack
* - For closing brackets: check if stack is empty or top doesn't match
* - Return true only if stack is empty after processing all characters
*
* Time Complexity: O(n) - Single pass through the string
* Space Complexity: O(n) - Stack can hold up to n/2 opening brackets in worst case
*/
bool isValid(string s) {
stack<char> st; // Stack to store opening brackets
// Hash map for O(1) bracket matching lookup
unordered_map<char, char> bracketMap = {
{')', '('},
{']', '['},
{'}', '{'}
};
for (char c : s) {
// If it's an opening bracket, push to stack
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
// If it's a closing bracket
if (st.empty() || st.top() != bracketMap[c]) {
return false; // No matching opening bracket or mismatch
}
st.pop(); // Remove the matched opening bracket
}
}
return st.empty(); // Valid if all brackets are matched
}
};