(Java)LeetCode-20. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


这道题蛮简单哈~用栈嘛,出栈的时候必须匹配,否则就是false~easy~



public boolean isValid(String s) {
		char[] ss = s.toCharArray();
		Stack<Character> st = new Stack<Character>();
		for(char ch : ss){
			switch (ch){
				case ')': 
					if(st.isEmpty())
						return false;
					if(st.pop() == '('){
						continue;
					}else{
						return false;
					}
				case ']':
					if(st.isEmpty())
						return false;
					if(st.pop() == '['){
						continue;
					}else{
						return false;
					}
				case '}':
					if(st.isEmpty())
						return false;
					if(st.pop() == '{'){
						continue;
					}else{
						return false;
					}
				case '{':
				case '(':
				case '[': 	st.push(ch);
							break;
			}
		}
		if(st.isEmpty())
			return true;
		else
			return false;
    }










阅读更多
个人分类: JAVA LeetCode
上一篇(Java)LeetCode-19. Remove Nth Node From End of List
下一篇(Java)LeetCode-21. Merge Two Sorted Lists
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭