先上题目:
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.
自己写的答案,测试通过
public class Solution {
public boolean isValid(String s) {
LinkedList<Character> stack = new LinkedList<Character>();
for(char c:s.toCharArray())
{
if(!stack.isEmpty())
{
if(stack.peek()==40&&c==41||stack.peek()==91&&c==93||stack.peek()==123&&c==125)
{
stack.pop();
}else
{
stack.push(c);
}
}else
{
stack.push(c);
}
}
return stack.isEmpty()?true:false;
}
}
本文介绍了一种使用Java实现的有效括号字符串验证算法。该算法利用栈数据结构来检查输入字符串中的括号是否正确配对。文章提供的代码示例能够处理圆括号、方括号及花括号,并判断其闭合顺序是否正确。
891

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



