給定一個只包括 '(',')','{','}','[',']'?的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認為是有效字符串。
示例 1:
輸入: "()"
輸出: true
示例?2:
輸入: "()[]{}"
輸出: true
示例?3:
輸入: "(]"
輸出: false
示例?4:
輸入: "([)]"
輸出: false
示例?5:
輸入: "{[]}"
輸出: true
思路:
初始化棧 S。
- 一次處理表達式的每個括號。
- 如果遇到開括號,我們只需將其推到棧上即可。這意味著我們將稍后處理它,讓我們簡單地轉到前面的 子表達式。
- 如果我們遇到一個閉括號,那么我們檢查棧頂的元素。如果棧頂的元素是一個 相同類型的 左括號,那么我們將它從棧中彈出并繼續處理。否則,這意味著表達式無效。
- 如果到最后我們剩下的棧中仍然有元素,那么這意味著表達式無效。
class Solution {// Hash table that takes care of the mappings.private HashMap<Character, Character> mappings;// Initialize hash map with mappings. This simply makes the code easier to read.public Solution() {this.mappings = new HashMap<Character, Character>();this.mappings.put(')', '(');this.mappings.put('}', '{');this.mappings.put(']', '[');}public boolean isValid(String s) {// Initialize a stack to be used in the algorithm.Stack<Character> stack = new Stack<Character>();for (int i = 0; i < s.length(); i++) {char c = s.charAt(i);// If the current character is a closing bracket.if (this.mappings.containsKey(c)) {// Get the top element of the stack. If the stack is empty, set a dummy value of '#'char topElement = stack.empty() ? '#' : stack.pop();// If the mapping for this bracket doesn't match the stack's top element, return false.if (topElement != this.mappings.get(c)) {return false;}} else {// If it was an opening bracket, push to the stack.stack.push(c);}}// If the stack still contains elements, then it is an invalid expression.return stack.isEmpty();}
}
?
?