LeetCode中Valid Parentheses的JAVA实现

来源:互联网 发布:在linux中安装oracle 编辑:程序博客网 时间:2024/06/05 11:35

先上题目:

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;
    }
}


0 0
原创粉丝点击