1,有效的括号,力扣:20. 有效的括号
题目:
思路:使用栈来解决,遍历字符串,比如字符串为“()”,先遍历,将“(”存入栈中,然后遇到元素“)”,就将左括号出栈,直到为空。
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(char c:s.toCharArray()){
if(c=='('){
stack.push(')');
}else if(c=='['){
stack.push(']');
}else if(c=='{'){
stack.push('}');
}else if(stack.isEmpty() || c!=stack.pop()){
return false;
}
}
return stack.isEmpty();
}
}
2, 最长有效括号,力扣:32. 最长有效括号
题目:
思路:也是使用栈来解决,由于该题是要找出有效连续的组合,需要注意的是,“连续”,所以我们可以先找到所有的可以匹配的索引号,然后再将索引号排序,选出最长序列的就是我们最长的有效括号的长度。
class Solution {
public int longestValidParentheses(String s) {
Deque<Integer> stack=new LinkedList<Integer>();
int count=0;
//防止第一个是“)”发生越界
stack.push(-1);
for(int i=0;i<s.length();i++){
//遍历到左括号就等待找到右括号
if(s.charAt(i)=='('){
stack.push(i);
}else{
//左右匹配就出栈
stack.pop();
//还要判断是否为空,空就将右括号放进来
if(stack.isEmpty()){
stack.push(i);
//否则就用全部减去无法匹配的括号
}else{
count=Math.max(count,i-stack.peek());
}
}
}
return count;
}
}
3,接雨水,力扣: 42. 接雨水
题目:
思路:改题目也是使用栈的方法来解决的,首先是先按照墙壁位置(也就是下标)来进行遍历,找到比前一个墙壁高的墙壁,当出现更高的墙壁,计算出可以接到的雨水,将前面更低的墙壁出栈。
class Solution {
public int trap(int[] height) {
int water = 0;
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<height.length;i++){
//条件:栈不为空,当前元素比栈顶大
while(!stack.isEmpty() && height[i]>height[stack.peek()]){
int bottom = stack.pop();
if(stack.isEmpty()){
break;
}
int left=stack.peek();
//左右墙
int leftHeight=height[left];
int rightHeight=height[i];
//水坑高度
int bottomHeight=height[bottom];
//底*高
water+=(i-left-1)*(Math.min(leftHeight,rightHeight)-bottomHeight);
}
stack.push(i);
}
return water;
}
}