java中的栈也是基于数组,和Queue不同的是Stack是后进先出即LIFO: last in first out。可以把栈想象成往箱子里放被子,最后放的被子最先被取出来。
Stack例子:判断表达式的括号、中括号、大括号的合法性
package com.test;
import java.util.Stack;
/**
* 栈的学习
*/
public class StackLearn {
public static void main(String[] args) {
String str = "(<>()}))";
System.out.println(balanced(str));
}
public static boolean balanced(String str) {
Stack<Character> stack = new Stack<>();
char[] array = str.toCharArray();
try {
for (char c : array) {
if (isLeft(c)) {
stack.push(c);
}
if (isRight(c)) {
char tmp = stack.pop();
char left = getLeft(c);
if (tmp != left) {
return false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static boolean isLeft(char c) {
return c == '[' || c =='{' || c == '(' || c == '<';
}
public static boolean isRight(char c) {
return c == ']' || c =='}' || c == ')' || c == '>';
}
public static char getLeft(char c) {
char left;
switch (c) {
case ']':
left = '[';
break;
case '}':
left = '{';
break;
case ')':
left = '(';
break;
default:
left = '<';
break;
}
return left;
}
}