"["
false
"[]"
true
要求:空间复杂度
,时间复杂度
。
function isValid( s ) {
// write code here
let obj = {
'(': ')',
'{': '}',
'[': ']'
}
let stack = [];
for (let i = 0; i < s.length; i++) {
if (Object.keys(obj).includes(s[i])) {
stack.push(s[i]);
}
else {
if (s[i] !== obj[stack.pop()]) {
return false
}
}
}
return !stack.length;
}
module.exports = {
isValid : isValid
}; /**
*
* @param s string字符串
* @return bool布尔型
* ({[( )]})
*/
function isValid( s ) {
// write code here
let stack=[];
const len=s.length;
const map = new Map();
map.set('{','}');
map.set('[',']');
map.set('(',')');
for(let i=0;i<len;i++){
if(map.has(s[i])){
stack.push(map.get(s[i]))
}else if(s[i]===stack[stack.length-1]){
stack.pop(map.get(s[i]));
}else{
return false;
}
}
if(stack.length)return false
return true
}
module.exports = {
isValid : isValid
}; let strL = ["(", "{", "["];
let strR = [")", "}", "]"];
let arr=[];
function isValid(s) {
// write code here
let i=0;
while(i<s.length){
console.log(strL.indexOf(s[i]))
if(strL.indexOf(s[i])!=-1){
arr.push(s[i]);
}else if(strL.indexOf(arr[arr.length-1])==strR.indexOf(s[i])){
arr.pop()
console.log(arr.length);
}else{
return false;
}
i++;
}
return arr.length==0?true:false;
}
module.exports = {
isValid: isValid,
}; function isValid( str ) {
let stack = [];
for(let s of str){
if(stack.length){
if(isMatch(stack[stack.length-1],s)){
stack.pop()
}else{
stack.push(s)
}
}else{
stack.push(s)
}
}
function isMatch(left,right){
if(left==='('&&right===')'||left==='{'&&right==='}'||left==='['&&right===']'){
return true
}
return false;
}
return !stack.length;
}