Leetcode [20] (Java): Valid parentheses

Source: Internet
Author: User

Tag: false char AC Ali Leetcode [] character if else check

title : valid parentheses sequence

Difficulty : Easy

topic content :

Given A string containing just the characters ‘(‘ ,,, ‘)‘ , and ‘{‘ ‘}‘ ‘[‘ ‘]‘ , determine if the input string is valid.

An input string is valid if:

    1. Open brackets must is closed by the same type of brackets.
    2. Open brackets must is closed in the correct order.

Note that a empty string is also considered valid.

translation : Given a string that contains only the characters ' (', ') ', ' {', '} ', ' [' and '] ', to determine whether the input string is valid.

The input string is valid:

The opening brackets must be closed with the same type of parentheses.

Opening parentheses must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()" Output:true

Example 2:

Input: "() []{}" Output:true

Example 3:

Input: "(]" Output:false

Example 4:

Input: "([)]" Output:false

Example 5:

Input: "{[]}" output:true

My idea : Data structure-The parentheses problem is a classic stack problem.

"Because there are three kinds of parentheses, and the nesting of three is complex, it is not easy to use shaping int as a judgment (left parenthesis + +, closing parenthesis--), such as" ([)] "If you use int then you will be judged correctly. 】

Algorithm--Using a stack, if the left parenthesis is placed directly, if the closing parenthesis, the pop stack to see if the corresponding opening parenthesis, otherwise return false; Finally check whether the stack is empty.

My Code :

1      Public BooleanIsValid (String s) {2         Char[] sc =S.tochararray ();3stack<character> stack =NewStack<character>();4          for(inti = 0; I<s.length (); i++) {5             Switch(Sc[i]) {6                  Case‘)‘:7                     if(Stack.empty () | | Stack.pop ()! = ' (')8                         return false;9                      Break;Ten                  Case‘}‘: One                     if(Stack.empty () | | Stack.pop ()! = ' {') A                         return false; -                      Break; -                  Case‘]‘: the                     if(Stack.empty () | | Stack.pop ()! = ' [') -                         return false; -                      Break; -                 default: + Stack.push (Sc[i]); -             } +         } A         returnstack.empty (); at}

My algorithm complexity : Time--o (n) space--o (n)

There was a problem with the encoding process :

1, the first use if else more cumbersome, and then switch to the first peek to judge the pop, can be directly optimized to determine the opposite conditions of the pop

For example:

if (!stack.empty () && stack.peek () = = ' [')    stack.pop (); Else    return false ; break;

Can be optimized into:

if (Stack.empty () | | Stack.pop ()! = ' ['    )returnfalse; break;

"In fact, there are no eggs." 】

2, Pop () should be judged before the stack is empty, if it is empty, should also return false;

3, in fact, the first can add a judgment, if the length of s is singular, then directly return false.

Reference Answer code :

1      Public BooleanIsValid (String s) {2         if((S.length () & 1) = = 1)3             return false;4stack<character> stack =NewStack<character>();5          for(CharC:s.tochararray ()) {6             if(c = = ' (')7Stack.push (') ');8             Else if(c = = ' {'))9Stack.push ('} ');Ten             Else if(c = = ' [') OneStack.push ('] '); A             Else if(Stack.isempty () | | Stack.pop ()! =c) -                 return false; -         } the         returnstack.isempty (); -}

Answer algorithm complexity : Time--o (n) space--o (n)

The answer thought : Actually the thought and my that almost "forcibly does not face", but this method uses the reverse thought: if is currently the opening parenthesis, then puts the corresponding right parenthesis, if is the right parenthesis the pop stack top is "oneself", otherwise return false. This reduces the code to determine whether the corresponding left parenthesis. But both algorithms are the same in complexity and in meaning, a better readability and a little more concise.

Leetcode [20] (Java): 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.