leetocde-栈
20. 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
class Solution {
public boolean isValid(String s) {
if(s==null || s.length()==0){
return true;
}
Map<Character,Character> map = new HashMap<Character, Character>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
Stack<Character> stack = new Stack<Character>();
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() || map.get(s.charAt(i))!=stack.peek() ){
return false;
}else{
stack.pop();
}
}
}
if(stack.empty()){
return true;
}
return false;
}
}
42. 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
class Solution {
public int trap(int[] height) {
if(height==null || height.length<3){
return 0;
}
int res = 0;
int leftMax = 0;
int rightMax = 0;
int i = 0;
int j = height.length-1;
while(i<j){
leftMax = Math.max(leftMax,height[i]);
rightMax = Math.max(rightMax,height[j]);
if(leftMax<rightMax){
res += leftMax - height[i];
i++;
}else{
res += rightMax - height[j];
j--;
}
}
return res;
}
}
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//bc/d//././/.."
Output: "/a/b/c"
class Solution {
public String simplifyPath(String path) {
if(path==null || path.length()<=1){
return path;
}
String[] each = path.split("/");
Stack<String> stack = new Stack<>();
for(String s:each){
if(s.equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
}else if(!s.equals(".")&&!s.isEmpty()){
stack.push(s);
}
}
String res = "";
if(stack.isEmpty()){
return "/";
}
while(!stack.isEmpty()){
String newPop = stack.pop();
res = "/" + newPop + res;
}
return res;
}
}
84. Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Example:
Input: [2,1,5,6,2,3]
Output: 10
class Solution {
public int largestRectangleArea(int[] heights) {
int max = 0;
if(heights==null || heights.length==0){
return max;
}
Stack<Integer> stack = new Stack<>();
for(int i=0;i<heights.length;i++){
if(stack.isEmpty()||heights[i]>heights[stack.peek()]){
stack.push(i);
}else{
// 右边界
int right = i;
int index = stack.pop();
//高度相同向左进行移动
while(!stack.isEmpty()&&heights[index]==heights[stack.peek()]){
index = stack.pop();
}
int leftmost = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max,(right-leftmost-1)*heights[index]);
i--;
}
}
// 数组处理完毕
// 有边界不变
int rightmost = stack.peek()+1;
while(!stack.isEmpty()){
int index = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max,heights[index]*(rightmost-left-1));
}
return max;
}
}
85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
class Solution {
public int maximalRectangle(char[][] matrix) {
int max = 0;
if(matrix==null || matrix.length==0||matrix[0].length==0){
return max;
}
int row = matrix.length;
int col = matrix[0].length;
int[] heights = new int[col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(matrix[i][j]=='0'){
heights[j]=0;
}else{
heights[j]+=1;
}
}
int area = largestMaximalRectangle(heights);
max = Math.max(max,area);
}
return max;
}
private int largestMaximalRectangle(int[] heights){
int max = 0;
if(heights==null || heights.length==0){
return max;
}
Stack<Integer> stack = new Stack<>();
for(int i=0;i<heights.length;i++){
if(stack.isEmpty()||heights[i]>heights[stack.peek()]){
stack.push(i);
}else{
// 右边界
int right = i;
int index = stack.pop();
//高度相同向左进行移动
while(!stack.isEmpty()&&heights[index]==heights[stack.peek()]){
index = stack.pop();
}
int leftmost = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max,(right-leftmost-1)*heights[index]);
i--;
}
}
// 数组处理完毕
// 有边界不变
int rightmost = stack.peek()+1;
while(!stack.isEmpty()){
int index = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max,heights[index]*(rightmost-left-1));
}
return max;
}
}
150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
class Solution {
public int evalRPN(String[] tokens) {
if(tokens==null || tokens.length==0){
return 0;
}
Stack<Integer> stack = new Stack<>();
for(String s:tokens){
if(s.equals("+")){
stack.push(stack.pop()+stack.pop());
}else if(s.equals("-")){
int b = stack.pop();
int a = stack.pop();
stack.push(a-b);
}else if(s.equals("*")){
stack.push(stack.pop()*stack.pop());
}else if(s.equals("/")){
int b = stack.pop();
int a = stack.pop();
stack.push(a/b);
}else{
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
}
155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
class MinStack {
/** initialize your data structure here. */
List<Integer> dataStack = new ArrayList<>();
List<Integer> minStack = new ArrayList<>();
public MinStack() {
}
public void push(int x) {
dataStack.add(x);
if(minStack.size()==0){
minStack.add(x);
}else{
int min = getMin();
if(x>min){
minStack.add(min);
}else{
minStack.add(x);
}
}
}
public void pop() {
minStack.remove(minStack.size()-1);
dataStack.remove(dataStack.size()-1);
}
public int top() {
return dataStack.get(minStack.size()-1);
}
public int getMin() {
return minStack.get(minStack.size()-1);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
224. Basic Calculator
mplement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
Example 1:
Input: "1 + 1"
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
class Solution {
public int calculate(String s) {
int res = 0;
int sign = 1;
int n = s.length();
int num = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c>='0'){
num = 10*num + (c-'0');
}else if (c== '+' || c=='-'){
res += sign * num;
num = 0;
sign = (c=='+')?1:-1;
}else if (c=='('){
stack.push(res);
stack.push(sign);
res = 0;
sign=1;
}else if (c== ')'){
res += sign*num;
num=0;
res *= stack.pop();
res += stack.pop();
}
}
res += sign*num;
return res;
}
}
225. Implement Stack using Queues
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
class MyStack {
/** Initialize your data structure here. */
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
for(int i=0;i<queue.size()-1;i++){
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
class MyQueue {
/** Initialize your data structure here. */
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack2.isEmpty() && stack1.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/