第一种方式:继承(ArrayList)
这种方式会存在问题:Array 里面所有的方法都可以访问,但有些方法对栈不适用
package com.weyan;
import com.weyan.list.ArrayList;
public class Stack<E> extends ArrayList<E> {
public void clear() {
list.clear();
}
public void push(E element) {
add(element);
}
public E pop() {
return remove(size - 1);
}
public E top() {
return get(size - 1);
}
}
验证结果:
第二种方式:ArrayList 作为为栈的一部分
import com.weyan.list.ArrayList;
public class Stack<E> {
private ArrayList<E> list = new ArrayList<>();
public void push(E element) {
list.add(element);
}
public E pop() {
return list.remove(list.size() - 1);
}
public E top() {
return list.get(list.size() - 1);
}
public boolean isEmpty() {
return list.isEmpty();
}
}
代码一:
package 栈;
import java.util.HashMap;
import java.util.Stack;
import org.omg.CORBA.PUBLIC_MEMBER;
public class _20_有效的括号 {
/** _20_有效的括号
* url:https://leetcode-cn.com/problems/valid-parentheses/solution/
*/
public Boolean isValid1(String s) {
Stack<Character> stack = new Stack<Character>();
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();
}
/** _20_有效的括号
* url:https://leetcode-cn.com/problems/valid-parentheses/solution/
*/
// private sta HashMap<Character, Character> map = new HashMap<Character, Character>();
// public _20_有效的括号() {
// //key - value
// map.put('(', ')');
// map.put('[', ']');
// map.put('{', '}');
// }
private static HashMap<Character, Character> map = new HashMap<Character, Character>();
static {
//key - value
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
}
public Boolean isValid2(String s) {
Stack<Character> stack = new Stack<Character>();
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;
char left = stack.pop();
if (c != map.get(left)) return false;
}
}
return stack.isEmpty();
}
}
网友评论