Valid Parentheses

来源:互联网 发布:淘宝服务市场推广 编辑:程序博客网 时间:2024/05/22 13:22

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.

用stack做。恩先复习下stack的用法。。。

public class Solution {    public boolean isValid(String s) {        Stack<Character> stack=new Stack<Character>();        for(int i=0;i<s.length();i++){            char c=s.charAt(i);            if(c=='('||c=='{'||c=='[')            stack.push(c);            else if(c==')'||c=='}'||c==']'){                if(stack.size()==0)                return false;                            char cpop=stack.pop();                if(c=='}'&&cpop=='{')                continue;                if(c==')'&&cpop=='(')                continue;                if(c==']'&&cpop=='[')                continue;                else return false;             }            }            return stack.size()==0;    }}



0 0
原创粉丝点击