-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0020-valid-parentheses.ts
More file actions
56 lines (49 loc) · 1.38 KB
/
Copy path0020-valid-parentheses.ts
File metadata and controls
56 lines (49 loc) · 1.38 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Blog:https://www.allenliservice.online/leetcode-js-20-valid-parentheses/
//<strong>Solution:</strong>
// 1. 運用「for...of」將input進行迴圈,比對錯誤即回傳false
// 2. 當「if條件」符合左括號時,push()放入空陣列中
// 3. 當「if條件」出現右括號時,pop()比對上一次儲存的左括號
// 4. 最後當宣告的空陣列長度為0時,回傳ture
// <strong>Code 1: BigO(n)</strong>
var isValid = function (s: string): boolean {
const array: string[] = [];
const map: Record<string, string> = {
")": "(",
"]": "[",
"}": "{",
};
for (let char of s) {
if (char === "(" || char === "[" || char === "{") {
array.push(char);
} else if (array.pop() !== map[char]) {
return false;
}
}
return !array.length;
};
/* <strong>Example 1</strong>
<pre style='background-color:#ggg'>
step.1
char = '('
array = [] => array = ['(']
step.2
char = ')'
array.pop = ['('] => map[char] = ['(']
array.length === 0 => true
</pre> */
// <strong>Code 2: BigO(n)</strong>
var isValid = function (s: string): boolean {
const array: string[] = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") {
array.push(")");
} else if (s[i] === "{") {
array.push("}");
} else if (s[i] === "[") {
array.push("]");
} else if (array.pop() !== s[i]) {
return false;
}
}
return array.length === 0;
};