Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]" Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]" 输出:false
提示:
1 <= s.length <= 104s仅由括号'()[]{}'组成
| Language | Runtime | Memory | Submission Time |
|---|---|---|---|
| typescript | 56 ms | 42.7 MB | 2022/05/02 13:34 |
function isValid(s: string): boolean {
const stack: ('{' | '[' | '(')[] = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === '{' || s[i] === '[' || s[i] === '(') {
stack.push(s[i] as '{' | '[' | '(');
} else {
const left = stack.pop();
if (left) {
if (s[i] === '}') {
if (left !== '{') {
return false;
}
} else if (s[i] === ']') {
if (left !== '[') {
return false;
}
} else {
if (left !== '(') {
return false;
}
}
} else {
return false;
}
}
}
return stack.length === 0;
};No notes