Valid Parentheses
https://leetcode.com/problems/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.
1 import java.util.HashMap; 2 import java.util.HashSet; 3 import java.util.Map; 4 import java.util.Set; 5 import java.util.Stack; 6 7 8 public class Solution { 9 public static boolean isValid(String s) { 10 int len=s.length(); 11 Stack<Character> stack=new Stack(); 12 Set<Character> l=new HashSet(); 13 Set<Character> r=new HashSet(); 14 Map<Character,Character> map=new HashMap(); 15 l.add('(');l.add('[');l.add('{'); 16 r.add(')');r.add(']');r.add('}'); 17 map.put('{', '}');map.put('(', ')');map.put('[', ']'); 18 for(int i=0;i<len;i++){ 19 char c=s.charAt(i); 20 if(l.contains(c)){ 21 stack.add(c); 22 } 23 else if(r.contains(c)){ 24 if(stack.isEmpty()||map.get(stack.peek())!=c){return false;} 25 stack.pop(); 26 } 27 else{return false;} 28 } 29 if(!stack.isEmpty()){return false;} 30 else{return true;} 31 } 32 public static void main(String[]args){ 33 System.out.println(isValid("{{}}")); 34 } 35 }