zoukankan      html  css  js  c++  java
  • leetcode:Valid Parentheses(有效括号匹配)

    Question:

    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.

    给定一个字符串仅仅包含这些字'(', ')', '{', '}', '[' and ']',  判定输入的字符串是否是可匹配的,括号必须以正确的顺序打开关闭,比如"()" and "()[]{}" 。

     

     

     

    算法思想:① 这个题首先会想到用栈进行存储操作,遇到左边的字符‘[’,'{',‘(’则进栈,如果遇到相反字符在栈不为空的前提下出栈,并且判断读到的字符是否和出栈的字符匹配,匹配的话继续,否则直接结束。

         ② 有一点儿在遍历输入字符时,如果栈为空了,表明肯定不能匹配。

         ③ 如果输入的字符遍历完毕,但是栈不为空,表明‘[’,'{',‘(这些字符多,也肯定不匹配。

    代码设计:

     1 class Solution {
     2     public boolean isValid(String s) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(s.length()%2==1)
     5             return false;//如果是奇数,一定不匹配
     6         Stack<Character> stack=new Stack<Character>();
     7         Character temp=null;
     8         for(int i=0;i<s.length();i++){  
     9             if(s.charAt(i)=='{'||s.charAt(i)=='['||s.charAt(i)=='('){
    10                 stack.push(s.charAt(i));//满足条件进栈
    11             }
    12             if(s.charAt(i)=='}'||s.charAt(i)==']'||s.charAt(i)==')'){
    13                 if(!stack.isEmpty())
    14                     temp=stack.pop(); //满足上述条件,出栈
    15                 else
    16                     return false;//循环还没结束 栈空了  一定不匹配
    17                 if((temp=='{'&&s.charAt(i)=='}')||(temp=='('&&s.charAt(i)==')')||(temp=='['&&s.charAt(i)==']')){
    18                     continue; //表示匹配,可以继续往下进行
    19                 }
    20                 else{
    21                     return false;  //不匹配。直接结束
    22                 }
    23             }
    24         }
    25         if(stack.isEmpty())  //有可能字符串已经遍历结束,但是栈并不为空,这表示不匹配,如果匹配的话肯定是栈为空并且字符串遍历完毕
    26             return true;
    27         else
    28             return false;
    29     }
    30 }

    2013-10-2402:16:14

  • 相关阅读:
    BOI 2002 双调路径
    BOI'98 DAY 2 TASK 1 CONFERENCE CALL Dijkstra/Dijkstra+priority_queue/SPFA
    USACO 2013 November Contest, Silver Problem 2. Crowded Cows 单调队列
    BOI 2003 Problem. Spaceship
    USACO 2006 November Contest Problem. Road Blocks SPFA
    CEOI 2004 Trial session Problem. Journey DFS
    USACO 2015 January Contest, Silver Problem 2. Cow Routing Dijkstra
    LG P1233 木棍加工 动态规划,Dilworth
    LG P1020 导弹拦截 Dilworth
    USACO 2007 February Contest, Silver Problem 3. Silver Cow Party SPFA
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/ValidParentheses.html
Copyright © 2011-2022 走看看