Valid Parentheses — Stack Bracket Matching
Advertisement
Problem 251 · Valid Parentheses
Difficulty: Easy · Pattern: Bracket Matching Stack
Solutions
// C
bool isValid(char* s) {
char stack[10001]; int top = 0;
for (int i = 0; s[i]; i++) {
if (s[i]=='(' || s[i]=='{' || s[i]=='[') stack[top++]=s[i];
else {
if (!top) return false;
char c = stack[--top];
if ((s[i]==')' && c!='(') || (s[i]==']' && c!='[') || (s[i]=='}' && c!='{'))
return false;
}
}
return top == 0;
}
// C++
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c=='(' || c=='{' || c=='[') st.push(c);
else {
if (st.empty()) return false;
char top = st.top(); st.pop();
if ((c==')' && top!='(') || (c==']' && top!='[') || (c=='}' && top!='{'))
return false;
}
}
return st.empty();
}
// Java
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c=='(' || c=='{' || c=='[') stack.push(c);
else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((c==')' && top!='(') || (c==']' && top!='[') || (c=='}' && top!='{'))
return false;
}
}
return stack.isEmpty();
}
# Python
def isValid(s):
stack = []
mapping = {')':'(', ']':'[', '}':'{'}
for c in s:
if c in mapping:
if not stack or stack[-1] != mapping[c]: return False
stack.pop()
else:
stack.append(c)
return not stack
Complexity
- Time: O(n)
- Space: O(n)
Advertisement