20. Valid Parentheses

    xiaoxiao2021-03-25  104

    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.

    括号匹配:借助栈,当进来字符为 ( { [左括号时 入栈,当进来字符为右括号} ])时,判断栈顶元素和该字符是否为一对,如果不是一对返回FALSE,否则继续;

    当栈空且还有字符时入栈,当栈空并且没有输入字符时返回true

    public boolean isValid(String s) { if(s.length()%2!=0) return false; Stack<Character> stack=new Stack(); stack.push(s.charAt(0)); char c; for(int i=1;i<s.length();i++){ c=s.charAt(i); if(stack.isEmpty()||c=='('||c=='{'||c=='['){ stack.push(c); }else { if((stack.peek()=='('&&c==')')||(stack.peek()=='{'&&c=='}')|| (stack.peek()=='['&&c==']')){ stack.pop(); }else{ return false; } } } if(stack.isEmpty()) return true; return false; }

    转载请注明原文地址: https://ju.6miu.com/read-15204.html

    最新回复(0)