Skip to content

Commit c20fe8d

Browse files
committed
solved: 20
1 parent 3a21c93 commit c20fe8d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

code/20.valid-parentheses.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// @leet start
2+
const PARENTIES = ['(', ')', '{', '}', '[', ']' ] as const
3+
type Parenty = typeof PARENTIES[number]
4+
5+
function isValid(str: string): boolean {
6+
const st: Parenty[] = []
7+
const m = {
8+
'{': '}',
9+
'[': ']',
10+
'(': ')'
11+
}
12+
13+
for(const _s of str){
14+
const s = _s as Parenty
15+
16+
/** 入ってるってことは開き括弧 */
17+
if(m[s]!=null) st.push(m[s]);
18+
19+
20+
/* stackの一番上の要素と入ってきた閉じ括弧が同じか確認 */
21+
else if(st.length>0 && st.at(-1) === s ) st.pop()
22+
23+
/* 違うならfalse */
24+
else return false
25+
}
26+
/* stackが空ならtrue */
27+
return st.length ===0
28+
};
29+
// @leet end

0 commit comments

Comments
 (0)