栈在括号匹配中的应用
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序任意,即([]())或者[([][])]等均为正确的表达式,[(])或([())均为不正确的格式。现在给一个表达式,判断其是否正确。
import java.util.Stack; public class BracketMatch { static final char[] dict = {'(', ')', '{', '}', '[', ']'}; public static void main(String[] args) { String str1 = "({[]})[]"; String str2 = "{([])}][(])"; if (match(str1)) System.out.println("合法"); else System.out.println("不合法"); if (match(str2)) System.out.println("合法"); else System.out.println("不合法"); } //出现的是左括号直接入栈,是右括号的话如果和栈顶元素不匹配则字符串不合法 public static boolean match(String str) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { char temp = str.charAt(i); if(temp == dict[0] || temp == dict[2] || temp == dict[4]) stack.push(temp); else{ if(stack.size() != 0 && dict[locate(stack.peek())+1] == temp) stack.pop(); else return false; } } if (stack.size() != 0) { return false; } else return true; } public static int locate(char _c) { int i; for (i = 0; i < dict.length; i++) { if (dict[i] == _c) break; } if (i < dict.length) return i; else return -1; } }
栈在递归中的应用
递归调用就是将原始问题转换为属性相同但是规模较小的问题。在递归调用的过程中,系统为每一层的返回点、局部变量、传入实参等开辟了递归工作栈来进行数据存储,递归次数过多容易造成栈溢出。下面是通过递归来计算斐波那契数列。
package com.dy.xidian; public class Fibric { public Fibric() { } public static void main(String[] args) { for (int i = 1; i <= 10; i++) System.out.print(fibric(i)+" "); } public static int fibric(int n) { if (n == 1) { return 1; } else if (n == 2) { return 1; } else { int t = fibric(n - 2) + fibric(n - 1); return t; } } }
下图是fibric(5)的计算过程