栈
Java Stack 类
栈是Vector的一个子类,它实现了一个标准的后进先出的栈。
栈只定义了默认构造函数,用来创建一个空栈。 栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。
创建一个空栈
Stack()
测试栈是否为空
boolean empty()
查看栈顶部的对象,但不从栈中移除它
Object peek( )
移除栈顶部的对象,并作为此函数的值返回该对象
Object pop( )
把项压入栈顶部
Object push(Object element)
返回对象在栈中的位置,以 1 为基数
int search(Object element)
用栈Stack 创建对象(类型不同)
Stack<Integer> stack = new Stack<>();
Stack<Character> stack = new Stack<>();
1.匹配字符串
import java.util.*;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
input = in.nextLine();
boolean bool = isValid(input);
if(bool == false) {
System.out.println("NO");
}else{
System.out.println("YES");
}
in.close();
}
public static boolean isValid(String input) {
Stack<Character> stack = new Stack<>();
for (char data:input.toCharArray()) {
if(data == '{' || data == '(' || data == '[') {
stack.push(data);
} else {
if(stack.empty() == true) {
return false;
}
if(data == '}' && stack.peek() == '{') {
stack.pop();
}else if(data == ')' && stack.peek() == '('){
stack.pop();
}else if(data == ']' && stack.peek() == '[') {
stack.pop();
}else{
return false;
}
}
}
return stack.empty();
}
}
2.后缀表达式
package Algorithm.one;
import java.util.Scanner;
import java.util.Stack;
class Solution {
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int a, b, c;
for(String ch : tokens) {
switch (ch) {
case "+" :
a = stack.pop();
b = stack.pop();
c = a + b;
stack.push(c);
break;
case "-" :
a = stack.pop();
b = stack.pop();
c = b - a;
stack.push(c);
break;
case "/" :
a = stack.pop();
b = stack.pop();
c = b / a;
stack.push(c);
break;
case "*" :
a = stack.pop();
b = stack.pop();
c = a * b;
stack.push(c);
break;
default:
int temp = Integer.parseInt(ch);
//字符转int
stack.push(temp);
}
}
return stack.peek();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num;
num = in.nextInt();
String[] tokens = new String[num];
for(int i = 0; i < num; i++) {
tokens[i] = in.next();
}
System.out.println(evalRPN(tokens));
}
}
int型与string型相互转换
String转换为int型
//convert str(String) to i(int)
String str;
int i = Integer.parseInt(str);
int型转换为String
//conver i(int) to str(String)
int i;
String str = i.toString();
int型转Integer
int i;
Integer j = Integer.valueOf(i);
Integer型转int型
Integer t;
int n = t.intValue();
3.最长括号串(栈存下标)
最长字符串,首先应该想到如何存入需要重置count的位置。栈先存放一个-1(下标用于计数)为了处理)()()(
,当第一个字符为右括号时,匹配消掉,存入新的异常字符")"
的下标,记录新位置(count = 0)。每一个新匹配成功的字符串在栈不为空的情况下,减去顶端的元素即可实现2到4,4到8的递增计数。
package Algorithm.one;
import java.util.Scanner;
import java.util.Stack;
/**
* @Author: ym
* @Date 2021/10/17 15:55
*/
class Solution {
public static int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int count = 0;
int maxNum = 0;
int i = 0;//默认
stack.push(-1);
for (char data : s.toCharArray()) {
if(data == '(') {
stack.push(i);
} else {
stack.pop();
if(stack.isEmpty()) {
count = 0;
stack.push(i);
}else{
count = i - stack.peek();//减去顶端的数
maxNum = Math.max(count, maxNum);
}
}
i++;
}
return maxNum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
input = in.nextLine();
System.out.println(longestValidParentheses(input));
in.close();
}
}
4、最小栈
在Java中,一共有8种基本数据类型:
整数型:int , short , long , byte
浮点型:float , double
字符类型:char
表示真值的类型:boolean
(String属于Java中的字符串类型,是一个引用类型,并不属于基本的数据类型)
Integer.MAX_VALUE表示int数据类型的最大取值数:2 147 483 647
Integer.MIN_VALUE表示int数据类型的最小取值数:-2 147 483 648
注意!!!pop、top 和 getMin 操作总是在 非空栈 上调用。
新建两个栈,一个存放数值,一个存放每个数值对应的当时的最小值,达到一一对应的关系。
package Algorithm.one;
import java.util.Deque;
import java.util.LinkedList;
/**
* @Author: ym
* @Date 2021/10/18 14:36
*/
class MinStack {
Deque<Integer> minStack;
Deque<Integer> stack;
public MinStack() {
minStack = new LinkedList<Integer>();
stack = new LinkedList<Integer>();
minStack.push(Integer.MAX_VALUE);
//使用栈首先添加一个数值,pop、top 和 getMin 操作总是在 非空栈 上调用。
}
public void push(int val) {
stack.push(val);
minStack.push(Math.min(minStack.peek(),val));
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
public static void main(String[] args) {
MinStack obj = new MinStack();
obj.push(6);
obj.push(5);
obj.push(3);
System.out.println(obj.top());
System.out.println(obj.getMin());
}
}
5.括号的最大嵌套深度
进栈的左括号加一,碰到消掉减一,记录最大的深度。
package Algorithm.one;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println(getStack(s));
in.close();
}
public static int getStack(String s) {
Stack<Character> stack = new Stack();
int len = 0;
int maxlen = 0;
for(char ch : s.toCharArray()) {
if(ch == '(') {
if(stack.isEmpty()) {
stack.push(ch);
len++;
continue;
}
stack.push(ch);
len++;
maxlen = Math.max(maxlen, len);
}else if(ch == ')' && stack.peek() == '('){
stack.pop();
len--;
}
}
return maxlen;
}
}
6.平衡括号字符串的最少插入次数
以左括号为计数,来消除右括号。当一个右括号出现,先看前面有没有与之匹配娥左括号,若没有,则加一个左括号;若有,则看下一位是否为右括号;
若无右括号,加一达成三个一组,若有右括号,跳过下一个右括号,看下一组。
最后看左括号有多少没有被一组一组消掉的。
class Solution {
public int minInsertions(String s) {
int left = 0;