码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 20. Valid Parentheses

时间:2018-10-13 11:43:02      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:push   str   ons   div   input   sed   closed   ash   java   

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

标签:push   str   ons   div   input   sed   closed   ash   java   

原文地址:https://www.cnblogs.com/flowingfog/p/9782171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!