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; }