public boolean isValid(String s) {
if (s == null) {
return false;
}
Map<Character, Character> map = new HashMap<>();
map.put(')','(');
map.put('}','{');
map.put(']','[');
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '{' ||c == '[' || c == '(') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char p = stack.pop();
if (map.get(c) != p) {
return false;
}
}
}
return stack.isEmpty();
}
// 用棧實現(xiàn)隊列,棧是FILO,隊列是FIFO
static class MyQueue {
int[] arr;
int defaultLength = 10;
int currentLength = 0;
int length;
/** Initialize your data structure here. */
public MyQueue() {
arr = new int[defaultLength];
length = defaultLength;
}
/** Push element x to the back of queue. */
public void push(int x) {
if (currentLength == length) {
// 擴容
int[] newArr = new int[arr.length * 2];
for (int i = 0; i < arr.length; i ++) {
newArr[i] = arr[i];
}
arr = newArr;
}
arr[currentLength++] = x;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int value = arr[0];
currentLength --;
for (int i = 0; i < currentLength ; i ++) {
arr[i] = arr[i + 1];
}
return value;
}
/** Get the front element. */
public int peek() {
return arr[0];
}
/** Returns whether the queue is empty. */
public boolean empty() {
return currentLength == 0;
}
}