- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbracket-match.ts
47 lines (42 loc) · 1.12 KB
/
bracket-match.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* @description 字符串括号匹配
* @author tangc1
* @date 2022-04-30 15:39:49
*/
functionisMatch(left: string,right: string): boolean{
if(left==='('&&right===')')returntrue
if(left==='['&&right===']')returntrue
if(left==='{'&&right==='}')returntrue
returnfalse
}
/**
* @description
* param {String} str
* return {Boolean} boolean
*/
exportfunctionbracketMatch(str: string): boolean{
constlength=str.length
if(length===0)returntrue
constleftSymbols='([{'
constrightSymbols=')]}'
letstack=[]
for(leti=0;i<length;i++){
consts=str[i]
if(leftSymbols.includes(s)){
// 左括号,入栈
stack.push(s)
}
if(rightSymbols.includes(s)){
// 右括号,判断栈顶是否出栈
consttop=stack[stack.length-1]
if(isMatch(top,s)){
stack.pop()
}else{
returnfalse
}
}
}
returnstack.length===0
}
// const str = '(e{r}[]])'
// console.info(bracketMatch1(str));