-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem.ts
More file actions
39 lines (32 loc) · 1.06 KB
/
Copy pathproblem.ts
File metadata and controls
39 lines (32 loc) · 1.06 KB
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
function getReversedBracket(ch : string) {
// Logic Check the Revesed Bracket
const map: Record<string, string> = {
')': '(',
'}': '{',
']': '[',
'(': ')',
'{': '}',
'[': ']'
};
return map[ch];
}
function isLeftBracket(ch : string) : boolean {
// logic check if is there is the left Bracket
return ch === '(' || ch === '{' || ch === '[';return true;
}
function CheckValidBracket(bracket_string: string, S: string[] = []): boolean {
for (const bracket of bracket_string) {
const rev = getReversedBracket(bracket);
if (isLeftBracket(bracket)) {
S.push(bracket);
} else {
if (S.length === 0) return false; // stack empty = mismatch
const top = S.pop();
if (top !== rev) return false; // mismatch
}
}
return S.length === 0; // valid only if nothing left unmatched
}
console.log(CheckValidBracket("([]{})")); // true
console.log(CheckValidBracket("([)]")); // false
console.log(CheckValidBracket("(")); // false