import java.util.ArrayList;
class Solution {
public static boolean isValid(String s) {
Stack stack = new Stack();
for (char c : s.toCharArray()) {
if (stack.isEmpty() || !isPair((char) stack.peek(), c)) {
stack.push(c);
} else {
stack.pop();
}
}
if (stack.isEmpty()) return true;
return false;
}
public static boolean isPair(char a, char b) {
if (a == '(' && b == ')') return true;
if (a == '{' && b == '}') return true;
if (a == '[' && b == ']') return true;
return false;
}
public static void main(String[] args) {
boolean b = isValid("()[]{}");
System.out.println(b);
}
}
class Stack<T> {
ArrayList<T> list = new ArrayList<T>();
public void pop() {
list.remove(list.size() - 1);
}
public void push(T data) {
list.add(data);
}
public <T> T peek() {
if (!list.isEmpty()) {
return (T) list.get(list.size() - 1);
}
return null;
}
public boolean isEmpty() {
return list.isEmpty();
}
}
import java.util.ArrayList;
import java.util.Stack;
class Solution {
public static boolean isValid(String s) {
Stack stack = new Stack();
for (char c : s.toCharArray()) {
if (stack.isEmpty() || !isPair((char) stack.peek(), c)) {
stack.push(c);
} else {
stack.pop();
}
}
if (stack.isEmpty()) return true;
return false;
}
public static boolean isPair(char a, char b) {
if (a == '(' && b == ')') return true;
if (a == '{' && b == '}') return true;
if (a == '[' && b == ']') return true;
return false;
}
}
知识点:
1:栈的使用
2:自定义栈用到了java泛型:本质是参数化类型
3:java.util.Stack类class Stack<E> extends Vector<E> 线程安全的
4:java中线程安全的:Vector和HashTable
给几乎所有的public方法都加上了synchronized关键字,由于加锁导致性能降低,被弃用了
Vector和HashTable被弃用后,它们被ArrayList和HashMap代替,但它们不是线程安全的:
线程安全的:(以下待完善,需代码测试,明白线程安全实现原理)
1):Collections工具类包装成线程安全
Collections.synchronizedList(new ArrayList<E>());
Set<E> synHashSet = Collections.synchronizedSet(new HashSet<E>());
Collections.synchronizedMap(new HashMap<K,V>());
2):java.util.concurrent
ConcurrentHashMap
3):
CopyOnWriteArrayList CopyOnWriteArraySet
它们是加了写锁的ArrayList和ArraySet,锁住的是整个对象,但读操作可以并发执行
4):
ConcurrentSkipListMap
ConcurrentSkipListSet
ConcurrentLinkedQueue
ConcurrentLinkedDeque