【Leetcode】算法总结——栈

【Leetcode】算法总结——栈

1. 栈

  1. Valid Parentheses(有效的括号)

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


```java
class Solution {
    public boolean isValid(String s) {
    	Stack<Character> stack=new Stack<Character>();
    	int len=s.length();
    	for(int i=0;i<len;i++) {
    		if(s.charAt(i)=='['||s.charAt(i)=='('||s.charAt(i)=='{') {
    			stack.push(s.charAt(i));
    		}else if (s.charAt(i)==']') {
    			//从栈中取出一个元素
                if(stack.empty()==true){
                    return false;
                }
    			char ch=stack.pop();
    			if(ch!='[') {
    				return false;
    				
    			}
    			
    		}else if(s.charAt(i)==')') {
                if(stack.empty()==true){
                    return false;
                }
    			char ch=stack.pop();
    			if(ch!='(') {
    				return false;
    				
    			}
    			
    		}else if(s.charAt(i)=='}'){
                if(stack.empty()==true){
                    return false;
                }
    			char ch=stack.pop();
    			if(ch!='{') {
    				return false;
    				
    			}
    			
    		}
    	}
    	
    	if(stack.empty()==true) {
    		return true;
    	}
    	return false;
        
    }

}
  1. Trapping Rain Water(接雨水)

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

思路:
使用一个栈,栈中元素是数组height的序号
遍历数组
当当前元素大于栈元素时,出栈
计算两堵墙height【i】与height【栈顶元素】的最小值min
计算两堵墙的之间的距离distance。
面积为 distance*min

class Solution {
    public int trap(int[] height) {
	    Stack<Integer> stack=new Stack<Integer>();
	    int sum=0;
	    int len=height.length;
	    
	    for(int i=0;i<len;i++){
	    	while(!stack.empty()&&height[stack.peek()]<height[i]) {
	    		//出栈
	    		int no=stack.pop();
	    		if(stack.empty()) {
	    			break;
	    		}
	    		int distance=i-stack.peek()-1;
	    		int min=height[i]<height[stack.peek()]?height[i]:height[stack.peek()];
	    		sum+=distance*(min-height[no]);
	    	}
	    	//将当前的入栈
	    	stack.push(i);
		  
	    }
	    
	   
	   
	   
		return sum;
		
        
    }



}
发布了34 篇原创文章 · 获赞 4 · 访问量 1339

猜你喜欢

转载自blog.csdn.net/zj20165149/article/details/103943078
今日推荐