昨天终于开始刷LeetCode的题了
按难度排序从简单开始
然后第一道题就是这道
隐约记得编译原理还是什么的课上讲用堆栈来实现
但具体的还是忘记了
看到答案才想起来是把左括号push 遇到右括号就和栈顶匹配 匹配pop不匹配就返回false
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
char[] parenthese = s.toCharArray();
for (char c : parenthese) {
if (c == '{' || c == '[' || c == '('){
stack.push(c);
}
else {
if (!stack.empty()){
char top = stack.peek();
if (top == '{' && c == '}' || top == '[' && c == ']' || top == '(' && c ==')') {
stack.pop();
}
else
return false;
}
else
return false;
}
}
return stack.empty();
}
Java的东西我都忘光了...
写的时候连stack怎么定义都要去查!!
第一次提交出了个错 忘记判断stack是否为空!!
然后就是九章的答案才知道有个东西叫Character
和char不一样...char是primitive type而Character是wrapper class
Wrapper Class:For every primitive type in Java, there is a built-in object type called a wrapper class. For example, the wrapper class for int is called Integer; for double it is called Double.
Wrapper classes are useful for several reasons:
- You can instantiate wrapper classes and create objects that contain primitive values. In other words, you can wrap a primitive value up in an object, which is useful if you want to invoke a method that requires an object type.
- Each wrapper class contains special values (like the minimum and maximum values for the type), and methods that are useful for converting between types.