Valid parentheses
Given A string containing just the characters ' (', ') ', ' {', '} ', ' [' and '] ', determine if the input string is valid.
The brackets must close in the correct order, "()" and "() []{}" is all valid but "(]" and "([)]" is not.
Ideas: The overall topic is more clear, is the parentheses are effective to make judgments, the algorithm is implemented with a stack, one-sided into the stack, after pairing out the stack, the last to determine whether the stack is empty, not NULL description is not the last pairing completed, return false.
The specific code is as follows:
public class Solution {public Boolean isValid (String s) {stack<character> st = new Stack<character> ;(); char[] ch = s.tochararray (); int len = ch.length; If the length is odd, it is definitely invalid if ((len & 1)! = 0) {return false; } for (int i = 0; i < len; i++) {if (St.isempty ()) {//stack is empty, directly into stack St.push (ch[i]); }else{//is not empty, it discusses whether the top element of the stack is paired with Ch[i]. Pairing is also out of the stack if (IsMatch (St.peek (), Ch[i]) {//Is paired st.pop ();//stack top element out of stack}else{ St.push (Ch[i]);//Unworthy to Stack}}} return St.isempty (); //A is the top element of the stack, B is the first element of the string public static Boolean IsMatch (char A, char b) {switch (a) {case ' (': if (b = = ') ) ') return true; else return false; Case ' {': if (b = = '} ') return true; else return false; Case ' [': if (b = = '] ') return true; else return false; Default:return false; } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 20.Valid Parentheses (valid brackets) ideas and methods for solving problems