标签:
题目:
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.
可以用map也可以不用
import java.util.HashMap; import java.util.Map; import java.util.Stack; public class ValidParentheses { /*//用map存对应关系 public boolean isValid(String s) { Map<Character, Character> map = new HashMap<Character, Character>(){ { put(')', '('); put(']', '['); put('}', '{'); } }; Stack<String> stack = new Stack<>(); int n = s.length(); for(int i=0; i<n; i++){ if(stack.empty()){ stack.push(s.charAt(i)); continue; } if(stack.peek() == (map.get(s.charAt(i)))){ stack.pop(); }else{ stack.push(s.charAt(i)); } } if(stack.empty()) return true; return false; }*/ public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); int n = s.length(); char c; for(int i=0; i<n; i++){ c = s.charAt(i); if(c==')' || c==']' || c=='}'){ if(stack.empty()) return false; char c2 = stack.peek(); if((c==')' && c2!='(') || (c==']' && c2!='[') || (c=='}' && c2!='{')){ return false; } stack.pop(); }else{ stack.push(c); } } if(stack.empty()) return true; return false; } }
LeetCode | #20 Valid Parentheses
标签:
原文地址:http://blog.csdn.net/allhaillouis/article/details/43114577