Java algorithm-parentheses problem

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.