I. Title Description:
20. Effective brackets given a include only ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective.
A valid string must meet the following requirements:
- An open parenthesis must be closed with a close parenthesis of the same type.
- The left parentheses must be closed in the correct order.
Example 1:
Input: s = “()” output: true
Example 2:
Input: s = “()[]{}” Output: true
Example 3:
Input: s = “(]” Output: false
Example 4:
Input: s = “([)]” Output: false
Example 5:
Input: s = “{[]}” Output: true
Ii. Analysis of Ideas:
- Declare an array ARR to store the elements of a string
- Determine if the last element of arr and s.charat (I) form a pair of parentheses as you traverse the string.
- Arr.pop () if a pair of parentheses can be formed.
- Otherwise the arr. Push (s.c harAt (I)).
- Finally, check whether the array is empty, and if it iss 是 Valid parenthesesOtherwise it is not
Iii. AC Code:
/ * * *@param {string} s
* @return {boolean}* /
var isValid = function(s) {
let arr = s? [s.charAt(0] : [];for(let i = 1; i < s.length; i++) {
let str = s.charAt(i);
switch(str) {
case '] ':
str = '[';
break;
case '} ':
str = '{';
break;
case ') ':
str = '(';
break;
}
if(arr[arr.length - 1] === str && s.charAt(i) ! == str) { arr.pop(); }else{ arr.push(s.charAt(i)); }}return arr.length === 0
};
Copy the code
Iv. Summary:
This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign