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

  • 相关阅读:
    Python使用struct处理二进制
    ProtoBuf与Python结合使用初步
    智能指针shared_ptr的用法
    C++模板
    mac 安装protobuf,并编译为java,c++,python
    java的HashCode方法
    JVM的内存结构
    HashSet与TreeSet的比较
    面向对象的特征有哪些方面?
    Collection与Collections的区别是什么?
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/ValidParentheses.html
Copyright © 2011-2022 走看看