題目來源於 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.
給定一個字串, 只包括 '(',')','{','}','[',']',判斷字串是否有效
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. 左括號必須以正確的順序閉合
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: true
複製程式碼
題目解析
- 遍歷字串
- 遇到左括號,則將其壓入棧中
- 如果遇到右括號:
- 當前棧為空,直接返回false;
- 當前右括號對應的左括號,與棧頂元素不相等,直接返回false
- 迴圈結束之後,判斷棧是否為空,不為空返回false
附上提交結果:
程式碼實現
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();
}
}
複製程式碼