给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses1 package stack_queue; 2 3 import java.util.Stack; 4 5 public class ValidParentheses { 6 public boolean isValid(String s) { 7 Stackleft = new Stack<>(); 8 char[] arrchar = s.toCharArray(); 9 for(char c : arrchar) {10 if(c == '(' || c == '[' || c == '{') {11 left.push(c); 12 } else {13 if(left.isEmpty()) {14 return false; 15 }16 char l = left.pop();17 boolean res1 = (l == '(') && (c == ')');18 boolean res2 = (l == '[') && (c == ']');19 boolean res3 = (l == '{') && (c == '}');20 if(res1 || res2 || res3) {21 continue; 22 }else {23 return false;24 }25 }26 }27 return left.isEmpty();28 }29 }