1、20题判断有效括号
var isValid = function(s) {
let stack=[];
for(let i=0;i<s.length;i++){
const start=s[i];
if(s[i]==="(" || s[i]==="{" || s[i]==="["){
stack.push(s[i]);
}else{
const end=stack[stack.length-1];
if((start ==='(' && end===')')||(start ==='{' && end==='}')||(start ==='[' && end===']')){
stack.pop();
}else{
return false;
}
}
}
// 入栈和出栈是匹配的,stack.length===0
return stack.length===0;
};
let a=isValid("{)")
console.log(a)
2、71题简化路径
var simplifyPath = function(path) {
let stack=[];
let str='';
let arr=path.split('/');
arr.forEach(val => {
if(val && val=='..'){
stack.pop()
}else if(val && val !='.'){
stack.push(val);
}
});
arr.length ? str='/'+stack.join('/'):str='/';
return str;
};
let c=simplifyPath("/a/./b/../../c/");
console.log(c);
4、1047.删除字符串中所有相邻重复项
var removeDuplicates = function(s) {
let stack=[];
for(v of s){
let prev=stack.pop();
if(prev !=v){
stack.push(prev);
stack.push(v);
}
}
return stack.join(''); //数组转化为字符串
};
let a=removeDuplicates('abbaca');
console.log(a);