很經典的問題,使用棧來解決,我這裏自己實現了一個棧,當然也可以直接用java自帶的Stack類。
自己實現的棧代碼:
import java.util.LinkedList;
class StackOne {
LinkedList<Object> data;
int top;
int maxSize;
StackOne(int size) {
// TODO Auto-generated constructor stub
top = -1;
maxSize = 100;
data = new LinkedList<Object>();
}
int getElementCount() {
return data.size();
}
boolean isEmpty() {
return top == -1;
}
boolean isFull() {
return top + 1 == maxSize;
}
boolean push(Object object) throws Exception {
if (isFull()) {
throw new Exception("棧滿");
}
data.addLast(object);
top++;
return true;
}
Object pop() throws Exception {
if (isEmpty()) {
throw new Exception("棧空");
}
top--;
return data.removeLast();
}
Object peek() {
return data.getLast();
}
}
判斷輸出是否有效:
public class Solution {
public static boolean isValid(String in) {
StackOne stackOne = new StackOne(100);
boolean result = false;
char[] inArray = in.toCharArray();
for (char i : inArray) {
if (i == '(' || i == '[' || i == '{') {
try {
stackOne.push(i);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
}
if (i == ')') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '(') {
result = true;
}
}
}
if (i == ']') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '[') {
result = true;
}
}
}
if (i == '}') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '{') {
result = true;
}
}
}
}
if (!stackOne.isEmpty()) {
result = false;
}
return result;
}
public static void main(String[] args) {
System.out.print(isValid("(}"));
}
}