LeetCode——20. 有效的括号
题目描述:
注:本分类博客中的所有代码可以直接拷贝到eclipise
代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
// 栈空就入栈
if (stack.isEmpty()) {
stack.push(array[i]);
// 判断是否匹配,匹配就弹出
} else if (isMarch(stack.peek(), array[i])) {
stack.pop();
} else {
stack.push(array[i]);
}
}
// 栈空说明匹配成功
return stack.size() == 0;
}
// 匹配栈顶与数组括号是否匹配
public boolean isMarch(char a, char b) {
if ((a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}')) {
return true;
}
return false;
}
}
public class MainClass {
public static String booleanToString(boolean input) {
return input ? "True" : "False";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
boolean ret = new Solution().isValid(line);
String out = booleanToString(ret);
System.out.print(out);
}
}
}