添加(0020.有效的括号.md):增加typescript版本

This commit is contained in:
Steve2020
2022-01-21 20:57:58 +08:00
parent 451fbe16f6
commit f54af7ff39

View File

@ -283,8 +283,60 @@ var isValid = function(s) {
};
```
TypeScript:
版本一:普通版
```typescript
function isValid(s: string): boolean {
let helperStack: string[] = [];
for (let i = 0, length = s.length; i < length; i++) {
let x: string = s[i];
switch (x) {
case '(':
helperStack.push(')');
break;
case '[':
helperStack.push(']');
break;
case '{':
helperStack.push('}');
break;
default:
if (helperStack.pop() !== x) return false;
break;
}
}
return helperStack.length === 0;
};
```
版本二:优化版
```typescript
function isValid(s: string): boolean {
type BracketMap = {
[index: string]: string;
}
let helperStack: string[] = [];
let bracketMap: BracketMap = {
'(': ')',
'[': ']',
'{': '}'
}
for (let i of s) {
if (bracketMap.hasOwnProperty(i)) {
helperStack.push(bracketMap[i]);
} else if (i !== helperStack.pop()) {
return false;
}
}
return helperStack.length === 0;
};
```
Swift
```swift
func isValid(_ s: String) -> Bool {
var stack = [String.Element]()