LeetCode 20. Valid Parentheses
Posted flowingfog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 20. Valid Parentheses相关的知识,希望对你有一定的参考价值。
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
package LeetCode;
import java.util.HashMap; import java.util.Map; import java.util.Stack; public class L20_ValidParentheses { public boolean isValid(String s) { int len=s.length(); Stack<Character> stack=new Stack<Character>(); if(len==0) return true; if(len%2!=0) return false; Map<Character,Character> map=new HashMap<Character,Character>(); map.put(‘(‘,‘)‘); map.put(‘[‘,‘]‘); map.put(‘{‘,‘}‘); map.put(‘)‘,‘ ‘); map.put(‘]‘,‘ ‘); map.put(‘}‘,‘ ‘); //stack.push(s.charAt(0)); for(int i=0;i<len;i++) { if (stack.empty())//栈为空 stack.push(s.charAt(i)); else if(s.charAt(i)!=map.get(stack.peek()))//或输入与栈顶不匹配 stack.push(s.charAt(i)); else stack.pop(); } if(stack.empty()) return true; else return false; } public static void main(String[] args){ L20_ValidParentheses l20=new L20_ValidParentheses(); String test="([)]"; boolean result=l20.isValid(test); System.out.println(result); } }
以上是关于LeetCode 20. Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 20. Valid Parentheses
[LeetCode]20. Valid Parentheses
[LeetCode]20 Valid Parentheses 有效的括号