題目來源於 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();
}
}
複製代碼