【力扣】20. 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。示例 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(); }
一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻