Valid Parentheses(java实现)

来源:互联网 发布:大众软件停刊了吗 编辑:程序博客网 时间:2024/05/17 02:14
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.Subscribe to see which companies asked this question

public class Solution{public static boolean isValid(String s){char[] ch = s.toCharArray();Stack<Character> stack = new Stack<>();for (int i = 0; i < ch.length; i++){if (stack.empty()){stack.push(ch[i]);}else{Character ch1 = stack.peek();Character ch2 = ch[i];if (ch1.equals('(') && ch2.equals(')') || ch1.equals('{') && ch2.equals('}')|| ch1.equals('[') && ch2.equals(']'))stack.pop();elsestack.push(ch[i]);}}if (stack.empty())return true;elsereturn false;}}

0 0