有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例1:
输入:
"()"
输出: true
示例2:
输入: "(){}"
输出: true
示例3:
输入:
"(]"
输出: false
示例4:
输入: "([)]"
输出: false
示例5:
输入: {[]}"
输出: true
function isValid(str) {
let len = str.length;
let arr = []
if(str.length % 2 !== 0 ) {
return false
}
for (let i = 0; i < len; i++) {
let letter = arr[arr.length -1]
switch(str[i]){
case "(" :
arr.push("(");
break
case "[" :
arr.push("[");
break
case "{" :
arr.push("{");
break
case ")" :
if(letter === "(") {
arr.pop()
}
break
case "]" :
if(letter === "[") {
arr.pop()
}
break
case "}" :
if(letter === "{") {
arr.pop()
}
break
}
}
return arr.length === 0
}
isValid("{{[}}}") //false
isValid("{{[]}}") //true
isValid("()[] ") //true
循环输出每一个字符,当到结尾时重头开始打印
function loopString(s) {
let i = 0
return function () {
if (i === s.length) i = 0
let res = s[i]
i++
return res
}
}
const bar = loopString('bar');
console.log(bar(), bar(), bar(), bar()); // 'b' 'a' 'r' 'b'
var shu = [
{id:1,name:"w",pid:0},
{id:2,name:"w",pid:0},
{id:3,name:"w",pid:1},
{id:4,name:"w",pid:1},
{id:5,name:"w",pid:2},
{id:6,name:"w",pid:1},
{id:7,name:"w",pid:5},
{id:8,name:"w",pid:5},
{id:9,name:"w",pid:5},
]
// 很简单的实现思路,找他爹
function arrToTree(arr) {
let res = [] //返回值
let obj = {}
// 借助obj 来承接arr 把 arr的item一一对应
// 1 :{id:1,name:"w",pid:0}...
arr.forEach(item => {
obj[item.id] = item;
})
//找爹环节 通过pid找item的爹 没爹就是根节点 直接push 有爹加children 再push
arr.forEach(item => {
let parent = obj[item.pid]
if(parent) {
parent.children ? parent : parent.children = []
parent.children.push(item)
}else{
res.push(item)
}
})
return res
}
arrToTree(shu)
let obj = [{
id:1,
name:"s",
pid:0,
children:[{ id:1,name:"s",pid:1},{ id:1,name:"s",pid:1}]
}]
function objToArr (obj) {
let res = []
// 他爹先进 儿子递归再进
obj.forEach(item => {
function loop (data) {
res.push({
id:data.id,
name:data.name,
pid:data.pid
})
if(data.children) {
for (const item of data.children) {
loop(item)
}
}
}
loop(item)
})
return res
}
// 如果不是数组包裹的对象则
let obj = {
id:1,
name:"s",
pid:0,
children:[{ id:1,name:"s",pid:1},{ id:1,name:"s",pid:1}]
}
function objToArr (obj) {
let res = []
function loop (data) {
res.push({
id:data.id,
name:data.name,
pid:data.pid
})
if(data.children) {
for(let i of data.children) {
loop(i)
}
}
}
loop(obj)
return res
}
// 防抖 :只执行最后一次
function debounce (fun,delay) {
let timer = null
return function () {
if(timer !==null) {
clearTimeout(timer )
}
timer = setTimeout(() => {fun.call(this)},delay)
}
}
//节流: 每隔几秒执行一次
function throttle(fun,delay) {
let flag = true
return function () {
if(flag){
setTimeout(()=> {
fun.call(this)
flag = true
},delay)
}
flag = false
}
}
var str = "asdasdasdasdasd";
function countLetter(str) {
const map = new Map()
for(let i=0; i<str.length; i++) {
const letter = str[i]
if(map.has(letter)) {
map.set(letter,map.get(letter)+1)
}else{
map.set(letter,1)
}
}
return map
}
countLetter(str)
Map(3) {'a' => 5, 's' => 5, 'd' => 5}