- Valid Parentheses
Easy
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
思路
利用栈的先进后出,后进先出的特点来判断
首先创建一个栈,如何char 为括号前半部分 将string的所有元素加入栈
如果为后半部分则用(peek())判断栈顶是否与字符匹配,如果匹配则弹出栈顶,如果不匹配直接返回false;
最后判断stack是否为空,如果括号一一配对,则stack最后为空
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i= 0; i< s.length();i++){
if(s.charAt(i) == '(' ||s.charAt(i) == '{' ||s.charAt(i) == '['){
stack.push(s.charAt(i));
}
else{
if(stack.isEmpty()){
return false;
}
if(s.charAt(i) ==')'&& stack.peek()!='('){
return false;
}
if(s.charAt(i) =='}'&& stack.peek()!='{'){
return false;
}
if(s.charAt(i) ==']'&& stack.peek()!='['){
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
}
知识点
栈中有两个基本的操作
推入 :从栈的顶端推入一个数据,依次往下推
弹出 :讲栈顶端的数据移除
栈的基本提点就是
先进后厨,后入先进
除了头尾的节点,每个元素都有一个先驱和一个后继
Stack.Peek 与 stack.pop 的区别
相同点:大家都返回栈顶的值。
不同点:peek 不改变栈的值(不删除栈顶的值),pop会把栈顶的值删除