有效的括号匹配
- 1.题目
- 2.图分析
- 3.代码实现
1.题目
2.图分析
3.代码实现
class Solution {public boolean isValid(String s) {//创建一个栈,来放左括号.Stack<Character> stack = new Stack<>();//遍历字符串,左括号放进栈for(int i = 0 ; i < s.length(); i++){char ch = s.charAt(i);//如果是左括号if(ch == '[' || ch == '(' || ch == '{'){stack.push(ch);}else{//证明是右括号if(stack.empty()){return false;}//开始匹配char ch2 = stack.peek();if((ch2=='('&&ch==')')||(ch2=='['&&ch==']')||(ch2=='{'&&ch=='}')){stack.pop();}else{return false;}}}if(!stack.empty()){return false;}return true;}
}