Valid parentheses
Category | Difficulty | Likes | Dislikes |
---|---|---|---|
algorithms | Easy (44.44%). | 2582 | – |
Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘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.
Personal answer key
var isValid = function(s) {
const obj = {
'{':'} '.'(':') '.'[':'] '
}
let arr = [];
for(let i = 0; i<s.length; i++){if(s[i]==='('||s[i]==='{'||s[i]==='['){
arr.push(s[i]);
}else if(s[i]! ==obj[arr[arr.length-1]]) {return false;
}else{ arr.pop(s[i]); }}return arr.length === 0;
};
Copy the code
Analysis of the
【 Concept of stack 】
- An operation that matches a class can define a one-to-one object.
- Arr. Length === 0 itself returns a Boolean value.