-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20. Valid Parentheses.html
117 lines (104 loc) · 3.44 KB
/
20. Valid Parentheses.html
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- // 执行用时 :80 ms, 在所有 JavaScript 提交中击败了65.96%的用户
// 内存消耗 :34.7 MB, 在所有 JavaScript 提交中击败了44.10%的用户 -->
<script>
// 单一类型的括号()
// ()[]{}
// true
const { log } = console;
/*var isValid = function(s) {
let array = s.split('');
let left = 0;
// log(array);
for (let index = 0; index < array.length; index++) {
if(array[index]==='('){
left++;
}
if(array[index]===')'){
if(left===0){
return false;
}else{
left--;
}
}
}
if(left===0){
return true;
}else{
return false;
}
}; */
// log( isValid('()(())()()((()))') );
// {[]}
var isValid = function (s) {
let array = s.split('');
let stack = [];
let left = 0;
for (let index = 0; index < array.length; index++) {
if (array[index] === '(' || array[index] === '{' || array[index] === '[') {
stack.push(array[index]);
}
//
// || array[index] === '}' || array[index] === ']'
if (array[index] === ')' ) {
if(stack.length===0){
return false;
}
if(stack[stack.length-1]==='('){
stack.pop(stack[stack.length-1]);
}else{
return false;
}
}else if(array[index] === '}'){
if(stack.length===0){
return false;
}
if(stack[stack.length-1]==='{'){
stack.pop(stack[stack.length-1]);
}else{
return false;
}
}else if(array[index] === ']'){
if(stack.length===0){
return false;
}
if(stack[stack.length-1]==='['){
stack.pop(stack[stack.length-1]);
}else{
return false;
}
}
}
if(stack.length>0){
return false;
}else{
return true;
}
};
log( isValid('(])') );
// "(])"
/* var isValid = function (s) {
var map = {
"(": ")",
"[": "]",
"{": "}"
}
var leftArr = []
for (var ch of s) {
if (ch in map) leftArr.push(ch); //为左括号时,顺序保存
else { //为右括号时,与数组末位匹配
if (ch != map[leftArr.pop()]) return false;
}
}
return !leftArr.length //防止全部为左括号
}; */
</script>
</body>
</html>