题目来源于 LeetCode 上第 20号(Valid Parentheses)问题:有效的括号。题目难度为 Easy。面试
题目地址:https://leetcode.com/problems/valid-parentheses/数组
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.bash
给定一个字符串, 只包括 '(',')','{','}','[',']',判断字符串是否有效ide
An input string is valid if:post
有效字符串须要知足如下条件:ui
Open brackets must be closed by the same type of brackets. 左括号必须用相同类型的右括号闭合spa
Open brackets must be closed in the correct order. 左括号必须以正确的顺序闭合3d
Note that an empty string is also considered valid.code
注意空字符串可被认为是有效字符串。cdn
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
复制代码
附上提交结果:
class Solution {
public boolean isValid(String s) {
if (s == null) return false;
Stack<Character> stack = new Stack();
//遍历字符串
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
//遇到左括号,则将其压入栈中
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
//当前栈为空,直接返回false
if (stack.isEmpty()) return false;
char top = stack.pop();
char bracket = '0';
if (c == ')') {
bracket = '(';
} else if (c == '}') {
bracket = '{';
} else if (c == ']') {
bracket = '[';
}
//当前右括号对应的左括号,与栈顶元素不相等,直接返回false
if (top != bracket) {
return false;
}
}
}
return stack.isEmpty();
}
}
复制代码