The following code is used to determine whether the parentheses in a string match the so-called match refers to the different types of parentheses must be left and right, can contain each other, but not cross
For example:.. (.. [..]..).. to be allowed; (... [...) ....].... It's forbidden.
For test cases in the main method, you should output: false true False false
Public classParentheses Problem { Public StaticBooleanIsgoodbracket(String s) {Stack<character> A =NewStack<character> (); for(inti =0; I < s.length (); i++) {Charc = S.charat (i);if(c = =' (')//Add the matching parentheses of each first matching brace to the stackA.push (' ) ');if(c = =' [') A.push ('] ');if(c = =' {') A.push ('} ');if(c = =' ) '|| c = ='] '|| c = ='} ') {//When you encounter the closing parenthesis, make a judgment if(a.size () = =0)//Is no data in the stack return false;//Fill in the blanks if(A.pop ()! = c)//If inconsistent with pop-ups, overlapping occurs return false; } }if(A.size ()! =0)//To the last stack also has elements, also belong to the mismatched type return false;//Fill in the blanks return true; } Public Static void Main(string[] args) {System. out. println (Isgoodbracket ("... (.. [.)..]. {. (..).} ...")); System. out. println (Isgoodbracket ("... (.. [...]. (.).). {. (..).} ...")); System. out. println (Isgoodbracket ("..... [...]. (.).) {. (..).} ...")); System. out. println (Isgoodbracket ("... (.. [...]. (.).) {. (..) ....")); }}
Java algorithm-parentheses problem