概念
栈是一种线性结构,要求只能在一端进行操作 (就是这么设计的)
入栈 push
往栈中添加元素
入栈 pop
从栈中移除元素
设计
可以用 动态数组 也可以链表
接口设计
练习
有效括号
方案一 while循环字符串不停替换
public boolean isValid2(String s) {
while (s.contains("{}")
|| s.contains("[]")
|| s.contains("()")) {
s = s.replace("{}", "");
s = s.replace("()", "");
s = s.replace("[]", "");
}
return s.isEmpty();
}
方案二
public boolean isValid1(String s) {
Stack<Character> stack = new Stack<>();
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') { // 左括号
stack.push(c);
} else { // 右括号
if (stack.isEmpty()) return false;
char left = stack.pop();
if (left == '(' && c != ')') return false;
if (left == '{' && c != '}') return false;
if (left == '[' && c != ']') return false;
}
}
return stack.isEmpty();
}
优化方案二 hashmap
private static HashMap<Character, Character> map = new HashMap<>();
static {
// key - value
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (map.containsKey(c)) { // 左括号
stack.push(c);
} else { // 右括号
if (stack.isEmpty()) return false;
if (c != map.get(stack.pop())) return false;
}
}
return stack.isEmpty();
}