文章目录
- 一、栈的模拟实现
- 数据结构栈的简单模拟实现java_浮云过海的博客-CSDN博客
- 二、三道经典算法题
- 1.有效的括号匹配
- 2.逆波兰表达式求值
- 3.栈的压入,弹出序列
1:有效的括号匹配
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
代码实现
public boolean isValid(String s) {
if (s == null || s.equals("")) {
return false;
}
Stack<Character> st = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
st.push(ch);
} else {
if (st.isEmpty()) {
return false;
}
char top = st.peek();
if (top == '(' && ch == ')' ||
top == '[' && ch == ']' ||
top == '{' && ch == '}') {
st.pop();
} else{
return false;
}
}
}
return st.isEmpty();
}
2:.逆波兰表达式求值
有效的算符包括 +
、-
、*
、/
。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
tokens = ["2","1","+","3","*"] 转化为算术表达式为:((2 + 1) * 3) = 9
代码实现
public int evalRPN(String[] tokens) {
if(tokens==null||tokens.length==0){
return 0;
}
Stack<Integer> stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
String s=tokens[i];
if(isNumber(s)){
int number=Integer.parseInt(s);
stack.push(number);
}else{
int m=stack.pop();
int n=stack.pop();
switch(s){
case "+":stack.push(n+m);
break;
case "-":stack.push(n-m);
break;
case "*":stack.push(n*m);
break;
case "/":stack.push(n/m);
break;
default:
}
}
}
return stack.pop();
}
public static boolean isNumber(String s){
return !(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"));
}
3.栈的压入,弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
[1,2,3,4,5],[4,5,3,2,1]
返回True
[1,2,3,4,5],[4,3,5,1,2]
返回False;
代码实现
public boolean IsPopOrder(int [] pushA, int [] popA) {
//非空检验
if (pushA == null || pushA.length == 0) {
return false;
}
Stack<Integer> stack = new Stack<>();
int j = 0;
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.isEmpty() && stack.peek() == popA[j]) {
j++;
stack.pop();
}
}
return stack.isEmpty();
}