LWC 50:678. Valid Parenthesis String

Source: Internet
Author: User
Tags valid
LWC 50:678. Valid parenthesis String

Portal : 678. Valid parenthesis String

problem:

Given A string containing only three types of characters: ' (', ') ' and ' * ', write a function to check whether this string is valid. We define the validity of a string by these rules:any left parenthesis ' (' must has a corresponding right parenthesis ') ’. Any right parenthesis ') ' must has a corresponding left parenthesis ' ('. Left parenthesis ' (' must go before the corresponding right parenthesis ') '. ' * ' could is treated as a single right parenthesis ') ' or a ' and a single left parenthesis ' (' or an empty string. An empty string is also valid.

Example 1:

Input: "()"
Output:true

Example 2:

Input: "(*)"
Output:true

Example 3:

Input: "(*))"
Output:true

Note: The string size is in the range [1, 100].
Discuss

Ideas:
The use of brute force search, the real need to traverse the state is "*", each encounter a star, there are three states: 1. No action, 2. Opening parenthesis +1, 3. Closing parenthesis +1, the legal state is always the opening parenthesis greater than or equal to the closing parenthesis, and the final output is left = = right.

The code is as follows:

 public boolean checkvalidstring (String s) {return robot (S.tochararray (), 0, 0, 0); } Boolean Robot (char[] CS, int i, int left, int. right) {if (I >= cs.length) {return to left
        = = right;
            } for (int j = i; j < cs.length; ++j) {if (cs[j] = = ' (') left++;
                else if (cs[j] = = ') ') {right++;
            if (right > left) return false;
                        } else {return robot (CS, J + 1, left, right) | | Robot (CS, J + 1, left + 1, right) ||
            Robot (CS, J + 1, left, right + 1);
    }} return left = = right; }

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.