【力扣】20. 有效的括號
阿新 • • 發佈:2020-08-14
給定一個只包括 '(',')','{','}','[',']'的字串,判斷字串是否有效。
有效字串需滿足:
左括號必須用相同型別的右括號閉合。
左括號必須以正確的順序閉合。
注意空字串可被認為是有效字串。示例 1:
輸入: "()"
輸出: true
示例2:輸入: "()[]{}"
輸出: true
示例3:輸入: "(]"
輸出: false
示例4:輸入: "([)]"
輸出: false
示例5:輸入: "{[]}"
輸出: true來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/valid-parentheses
時間複雜度:最差為:O(n) 空間複雜度:藉助了棧,O(n)
public boolean isValid(String s) { if(s == null || "".equals(s)){ return true; } Stack<Character> stack = new Stack<Character>(); stack.push(s.charAt(0)); for(int i = 1;i < s.length(); i++){ char current = s.charAt(i);if(')' == current || '}' == current || ']' == current){ if(stack.isEmpty()){ return false; } char temp = stack.peek(); //能夠對應上 if((temp == '(' && current == ')' ) || (temp == '[' && current == ']' ) || (temp == '{' && current == '}' )){ stack.pop(); }else { return false; } } else { stack.push(current); } } return stack.isEmpty(); }