标签:false sed lang switch OLE push else rac 字符
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, determine if the input string is valid.
An input string is valid if:
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "([)]"
Output: false
给定一个只包含括号的字符串,判断括号是否匹配。
用栈处理:是左半边括号则压入栈,是右半边括号则比较与栈顶是否匹配。最后检查栈是否清空。
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ‘(‘ || c == ‘[‘ || c == ‘{‘) {
stack.push(c);
} else if (c == ‘)‘) {
if (!stack.isEmpty() && stack.peek() == ‘(‘) {
stack.pop();
} else {
return false;
}
} else if (c == ‘]‘) {
if (!stack.isEmpty() && stack.peek() == ‘[‘) {
stack.pop();
} else {
return false;
}
} else {
if (!stack.isEmpty() && stack.peek() == ‘{‘) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
}
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
let stack = []
for (let c of s.split(‘‘)) {
switch (c) {
case ‘(‘:
case ‘[‘:
case ‘{‘:
stack.push(c)
break
case ‘)‘:
if (stack.length === 0 || stack.pop() !== ‘(‘) {
return false
}
break
case ‘]‘:
if (stack.length === 0 || stack.pop() !== ‘[‘) {
return false
}
break
case ‘}‘:
if (stack.length === 0 || stack.pop() !== ‘{‘) {
return false
}
break
}
}
return stack.length === 0
}
标签:false sed lang switch OLE push else rac 字符
原文地址:https://www.cnblogs.com/mapoos/p/13171278.html