题目:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are
not.
考察栈的基本使用,简单的入栈和出栈即可解决。刚看到了一种好玩的for循环格式,这里用一下。
public class Solution {
public boolean isValid(String s) {
Stack<Character> stackS = new Stack<Character>();
char[] arr = s.toCharArray();
for (char c : arr) {
if(stackS.isEmpty()){
stackS.push(c);
continue;
}
Character temp = stackS.pop();
// 配对时c不入栈
if (temp == '[' && c == ']') {
}
<span style="white-space:pre"> </span> else if (temp == '(' && c == ')') {
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span> else if (temp == '{' && c == '}') {
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span> // 不配对时c入
<span style="white-space:pre"> </span> else {
<span style="white-space:pre"> </span> stackS.push(temp);
<span style="white-space:pre"> </span> stackS.push(c);
<span style="white-space:pre"> </span> }
}
return stackS.isEmpty();
}
}
本文介绍了一种使用栈数据结构来验证括号是否正确匹配的方法。通过遍历输入字符串中的每一对括号,确保它们能够正确地打开和关闭。此算法适用于包含'(',')','{','}
144

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



