先上题目:
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;
}
}
时间: 2024-10-06 10:27:55