Skip to content

Commit 2df7bca

Browse files
committed
Add #0020 Valid Parentheses
1 parent df8dd5b commit 2df7bca

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../problems/0020-valid-parentheses
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../problems/0020-valid-parentheses
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import isValid from './valid-parentheses';
2+
3+
describe('20. Valid Parentheses', (): void => {
4+
test.each`
5+
s | expected
6+
${'()'} | ${true} }
7+
${'()[]{}'} | ${true}
8+
${'(]'} | ${false}
9+
${'([)]'} | ${false}
10+
${'{[]}'} | ${true}
11+
`('Expect $s to be $expected', ({ s, expected }): void =>
12+
expect(isValid(s)).toBe(expected)
13+
);
14+
});
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
interface Match {
2+
[left: string]: string;
3+
}
4+
5+
const DEFAULT_MATCHES: Match = {
6+
'(': ')',
7+
'[': ']',
8+
'{': '}',
9+
};
10+
11+
/**
12+
* 每個字符進入時,可能情況有:
13+
* 1. 左括號:在待比對清單中加入對應的右括號
14+
* 2. 右括號:如果待比對清單第一個字元跟這個右括號不相同,則錯誤;如果相同,則消去
15+
* 3. 其他字:錯誤
16+
*
17+
* 執行到最後,如果待比對清單已清空,則為正確
18+
*
19+
* 圖解 isValid('(){[]}')
20+
*
21+
* 步驟 | 當前字元 | 當前待比對清單 | 比對完之後的待比對清單
22+
* 1 ( '' ')'
23+
* 2 ) ')' ''
24+
* 3 { '' '}'
25+
* 4 [ '}' ']}'
26+
* 5 ] ']}' '}'
27+
* 6 } '}' ''
28+
*
29+
* 最終待比對清單為空,所以為正確
30+
*/
31+
function isValid(s: string, matches: Match = DEFAULT_MATCHES): boolean {
32+
let pendings = '';
33+
for (const char of s) {
34+
if (pendings[0] === char) {
35+
pendings = pendings.slice(1);
36+
continue;
37+
}
38+
39+
const match = matches[char] ?? null;
40+
if (match === null) {
41+
return false;
42+
}
43+
44+
pendings = match + pendings;
45+
}
46+
return pendings.length === 0;
47+
}
48+
49+
export default isValid;

0 commit comments

Comments
 (0)