zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    项目经验:如何做到不和产品打起来
    leetcode-剑指30-OK
    leetcode-剑指05-OK
    leetcode-剑指58-OK
    leetcode-剑指28-OK
    leetcode-剑指53-I
    leetcode-剑指18-OK
    leetcode-剑指15-OK
    leetcode-剑指27-OK
    leetcode-剑指17-OK
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4476006.html
Copyright © 2011-2022 走看看