LeetCode - Valid Parentheses

昨天终于开始刷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.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值