描述
Given a string 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.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
难度
Easy
题目链接:
https://leetcode.com/problems/valid-parentheses/
思路
思路比较简单,就是用一个栈,每遍历一个元素就压入栈中,如果满足条件就弹出。问题只在于如何编写,
public static void main(String...args) {
System.out.println(isValid("()"));
System.out.println(isValid("()[]{}"));
System.out.println(isValid("(]"));
System.out.println(isValid("([)]"));
System.out.println(isValid("{[]}"));
}
public static boolean isValid(String s) {
char[] cs = s.toCharArray();
LinkedList<Character> stack = new LinkedList<>();
for (char c : cs) {
Character top = stack.peek();
if (top != null && (top == '(' && c == ')'
|| top == '{' && c == '}'
|| top == '[' && c == ']')) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
这里使用 LinkedList 来模拟栈,不适用 Stack,因为后者对每个方法加锁,效率较低!

本文介绍了一个简单的算法,用于验证字符串中的括号是否正确配对。通过使用栈结构,该算法可以高效地检查括号的类型和顺序是否符合要求。文章提供了具体的代码实现,并通过几个示例说明了算法的有效性。
3610

被折叠的 条评论
为什么被折叠?



