20. Valid Parentheses
Given a string s containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = “()”
Output: true
Example 2:
Input: s = “()[]{}”
Output: true
Example 3:
Input: s = “(]”
Output: false
Constraints:
- 1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
- s consists of parentheses only ‘()[]{}’.
From: LeetCode
Link: 20. Valid Parentheses
文章来源:https://www.toymoban.com/news/detail-659709.html
Solution:
Ideas:
To determine if the string contains valid parentheses, we can use a stack. Here’s the approach:文章来源地址https://www.toymoban.com/news/detail-659709.html
- Create an empty stack.
- Traverse the string one character at a time.
- For each character:
- If it’s an opening bracket ((, {, or [), push it onto the stack.
- If it’s a closing bracket (), }, or ]), check if the stack is empty. If it’s empty, then there’s no matching opening bracket, so return false.
- If the stack is not empty, pop the top element and check if it matches the corresponding opening bracket for the current closing bracket. If not, return false.
- After processing all characters in the string, check if the stack is empty. If it’s empty, then all opening brackets have been matched, so return true. Otherwise, return false.
Code:
bool isValid(char * s) {
int n = strlen(s);
char *stack = (char *)malloc(n * sizeof(char));
int top = -1; // stack is empty initially
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
// Push the character onto the stack
stack[++top] = s[i];
} else {
// Check for matching opening bracket
if (top == -1) {
// No opening bracket to match
free(stack);
return false;
}
char openBracket = stack[top--]; // Pop the top of the stack
if (s[i] == ')' && openBracket != '(') {
free(stack);
return false;
}
if (s[i] == '}' && openBracket != '{') {
free(stack);
return false;
}
if (s[i] == ']' && openBracket != '[') {
free(stack);
return false;
}
}
}
bool result = (top == -1);
free(stack);
return result;
}
到了这里,关于LeetCode //C - 20. Valid Parentheses的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!