给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:输入: “()[]{}”
输出: true
示例 3:输入: “(]”
输出: false
示例 4:输入: “([)]”
输出: false
示例 5:输入: “{[]}”
输出: true
通过次数291,883提交次数699,868来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
class Solution {
public boolean isValid(String s) {
if (s == null) {
return true;
}
s = s.trim();
if (s.isEmpty()) {
return true;
}
Stack<Character> stack = new Stack<Character>();
int length = s.length();
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
char v = 0;
switch (c) {
case '(':
stack.push(c);
break;
case ')':
if (stack.isEmpty()) {
return false;
}
v = stack.pop();
if (v != '(') {
return false;
}
break;
case '[':
stack.push(c);
break;
case ']':
if (stack.isEmpty()) {
return false;
}
v = stack.pop();
if (v != '[') {
return false;
}
break;
case '{':
stack.push(c);
break;
case '}':
if (stack.isEmpty()) {
return false;
}
v = stack.pop();
if (v != '{') {
return false;
}
break;
default:
break;
}
}
return stack.isEmpty();
}
}
要点
直接使用JDK自带的容器Stack
,按照题目要求来实现,代码本身不复杂,所以不做过多的解释。
准备的用例,如下
private Solution t = null;
@Before
public void before() {
t = new Solution();
}
@Test
public void test001() {
assertTrue(t.isValid("()"));
}
@Test
public void test002() {
assertTrue(t.isValid("()[]{}"));
}
@Test
public void test003() {
assertFalse(t.isValid("(]"));
}
@Test
public void test004() {
assertFalse(t.isValid("([)]"));
}
@Test
public void test005() {
assertTrue(t.isValid("{[]}"));
}