LeetCode——Valid Parentheses

Posted slgkaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode——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.

原题链接:https://oj.leetcode.com/problems/valid-parentheses/

题目:给定一个仅包括‘(‘‘)‘‘{‘‘}‘‘[‘ 和 ‘]‘ 的字符串,检測输入的串是否合法。括号是否配对。

思路:使用一个栈。遇到左括号则压入。遇到右括号则与左括号检測是否匹配,不匹配即false,弹出顶元素,循环。

	public boolean isValid(String s){
		int len = s.length();
		if(len <= 1)
			return false;
		if(s.charAt(0) == ‘)‘ || s.charAt(0)==‘]‘ || s.charAt(0)==‘}‘)
			return false;
		Stack<Character> stack = new Stack<Character>();
		for(int i=0;i<len;i++){
			if(s.charAt(i) == ‘(‘ || s.charAt(i)==‘[‘ || s.charAt(i)==‘{‘)
				stack.push(s.charAt(i));
			else{
				if(stack.size() == 0)
					return false;
				if(s.charAt(i) == ‘)‘)
					if(stack.peek() != ‘(‘)
						return false;
				if(s.charAt(i) == ‘]‘)
					if(stack.peek() != ‘[‘)
						return false;
				if(s.charAt(i) == ‘}‘)
					if(stack.peek() != ‘{‘)
						return false;
				stack.pop();
			}
		}
		return stack.size() == 0;
	}








以上是关于LeetCode——Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

java https://www.hrwhisper.me/leetcode-remove-invalid-parentheses/ http://blog.csdn.net/qq508618087/

java https://www.hrwhisper.me/leetcode-remove-invalid-parentheses/ http://blog.csdn.net/qq508618087/

java https://www.hrwhisper.me/leetcode-remove-invalid-parentheses/ http://blog.csdn.net/qq508618087/

java https://www.hrwhisper.me/leetcode-remove-invalid-parentheses/ http://blog.csdn.net/qq508618087/

LeetCode Graph Valid Tree

LeetCode 125. Valid Palindrome