Problem Description
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The string is valid if all open brackets are closed in the correct order.
Examples
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Python Solution
def isValid(s: str) -> bool:
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
Java Solution
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack<>();
Map mapping = new HashMap<>();
mapping.put(')', '(');
mapping.put('}', '{');
mapping.put(']', '[');
for (char c : s.toCharArray()) {
if (mapping.containsKey(c)) {
char topElement = stack.empty() ? '#' : stack.pop();
if (topElement != mapping.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}
C++ Solution
class Solution {
public:
bool isValid(string s) {
stack stack;
unordered_map mapping = {
{')', '('},
{'}', '{'},
{']', '['}
};
for (char c : s) {
if (mapping.find(c) != mapping.end()) {
char topElement = stack.empty() ? '#' : stack.top();
stack.pop();
if (mapping[c] != topElement) {
return false;
}
} else {
stack.push(c);
}
}
return stack.empty();
}
};
JavaScript Solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const stack = [];
const mapping = {
')': '(',
'}': '{',
']': '['
};
for (let char of s) {
if (char in mapping) {
const topElement = stack.length === 0 ? '#' : stack.pop();
if (mapping[char] !== topElement) {
return false;
}
} else {
stack.push(char);
}
}
return stack.length === 0;
};
C# Solution
public class Solution {
public bool IsValid(string s) {
Stack stack = new Stack();
Dictionary mapping = new Dictionary() {
{')', '('},
{'}', '{'},
{']', '['}
};
foreach (char c in s) {
if (mapping.ContainsKey(c)) {
char topElement = stack.Count == 0 ? '#' : stack.Pop();
if (topElement != mapping[c]) {
return false;
}
} else {
stack.Push(c);
}
}
return stack.Count == 0;
}
}
Complexity Analysis
- Time Complexity: O(n) where n is the length of the string
- Space Complexity: O(n) to store the stack
Solution Explanation
This solution uses a stack data structure. Here's how it works:
- Create a stack to store opening brackets
- Create a mapping of closing brackets to their corresponding opening brackets
- For each character in the string:
- If it's a closing bracket, check if stack's top matches its opening bracket
- If it's an opening bracket, push it onto the stack
Key points:
- Stack helps maintain the order of brackets
- Mapping makes it easy to check matching brackets
- Empty stack at the end means valid string
- The solution handles all edge cases properly