Leetcode-valid parentheses

Source: Internet
Author: User

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"(]"And"([)]"Are not.

Solution:

1. If the left parenthesis appears, a matching right parenthesis must be followed.

2. If there is no left parenthesis, there must be no right parenthesis

For 1, open a stack to solve

For example, if there is a right brace, the left brace must already exist (the matching right brace is at the top of the stack)

Open a hashset to judge the right parenthesis.

 1     public boolean isValid(String s) { 2         if(s== null || s.length() ==0){ 3             return true; 4         } 5         Stack<Byte> brackets = new Stack<Byte>(); 6         HashSet<Byte> sets = new HashSet<Byte>(); 7         sets.add((byte) ‘)‘); 8         sets.add((byte) ‘]‘); 9         sets.add((byte) ‘}‘);10         byte [] sBytes = s.getBytes();11         for(int i =0;i<sBytes.length;i++){12             if(sBytes[i] == ‘(‘){13                 brackets.push((byte) ‘)‘);14                 continue;15             }16             if(sBytes[i] == ‘{‘){17                 brackets.push((byte) ‘}‘);18                 continue;19             }20             if(sBytes[i] == ‘[‘){21                 brackets.push((byte) ‘]‘);22                 continue;23             }24             if(sets.contains(sBytes[i])){25                 if(!brackets.isEmpty() && brackets.peek() == sBytes[i]){26                     brackets.pop();27                 }else{28                     return false;29                 }30             }31         }        32         return brackets.isEmpty();33     }

 

Leetcode-valid parentheses

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.