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.
java:
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i<s.length();i++){
char ss = s.charAt(i);
if (ss=='('||ss=='['||ss=='{'){
stack.push(ss);
}
else if (ss==')'||ss==']'||ss=='}'){
if (stack.size()==0) return false;
char cpop = stack.pop();
if (cpop=='('&&ss==')')
{
continue;
}
else if (cpop=='['&&ss==']')
{
continue;
}
else if (cpop=='{'&&ss=='}')
{
continue;
}
return false;
}
}
return stack.empty();
}
}
本文介绍了一种使用Java实现的有效括号匹配验证算法。通过栈结构处理输入字符串中的括号,确保每一对括号都能正确闭合。具体实现包括遍历字符串、判断括号类型并进行匹配等关键步骤。
6856

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



