Leetcode (): Valid parentheses

Source: Internet
Author: User

Valid parentheses: Given A string containing just the characters,,, ‘(‘ ‘)‘ , and ‘{‘ ‘}‘ ‘[‘ ‘]‘ , determine if the input string I S valid. The brackets must close in the correct order, and is all valid but and is not "()" "()[]{}" "(]" "([)]" .

Test Instructions: given a string, by,,,, ‘(‘ ‘)‘ ‘{‘ ‘}‘ ‘[‘ and‘]‘组成,判断这串字符串是不是有效的组合。

思路:使用栈来解决此题。遍历字符串,如果第一个字符为)} ]中的一个则直接返回false;否则将其压入栈中。接着处理下面的字符:

(1)如果是( { [中的一个则直接压入栈中

(2)如果是})]中的一个,则和栈顶元素比较:如果栈顶元素是遇到元素的匹配字符则栈顶元素出栈,否则返回false

最后判断栈是否为空,如果为空则返回true,否则返回false。

代码:

 Public BooleanIsValid (String s) {stack stack=NewStack (); if(S.length () <2)return false; String Temp= string.valueof (S.charat (0)); if(Temp.equals (")") | | Temp.equals ("}") | | Temp.equals ("]"))return false;  for(intI=0;i<s.length (); i++) {Temp=string.valueof (S.charat (i)); if(Temp.equals (") | | Temp.equals ("{") | | Temp.equals ("[") {Stack.push (temp); }                Else if(!Stack.isempty ()) {                Switch(temp) { Case")":                        if(("("). Equals (Stack.peek ())) {Stack.pop (); }Else {                                return false; }                         Break;  Case"}":                        if(("{"). Equals (Stack.peek ())) {Stack.pop (); }Else {                            return false; }                         Break;  Case"]":                        if(("["). Equals (Stack.peek ())) {Stack.pop (); }Else{                            return false; }                         Break; default:                        return false; }                }                Else {                    return false; }            } // for         if(Stack.isempty ()) {return true; }Else {            return false; }    }

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.