zoukankan      html  css  js  c++  java
  • LeetCode算法01 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.

    先解释一下:

    本题要求:给一个包含“{”,“[”,“(”,")","]","}"  String,判断一下输入的string 结构是否合法; 这些括弧必须遵循正确的规则。

    solution:

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }

    借着本体的答案讲解一下Stack类;

    Stack 为java.util包下类:

    构造方法

      Stack();创建一个空 Stack。 

    E push(E item)   
             把项压入堆栈顶部。   
    E pop()   
             移除堆栈顶部的对象,并作为此函数的值返回该对象。   
    E peek()   
             查看堆栈顶部的对象,但不从堆栈中移除它。   
    boolean empty()   
             测试堆栈是否为空。    
    int search(Object o)   
             返回对象在堆栈中的位置,以 1 为基数。  

     

     

  • 相关阅读:
    css设置页面内容不能被选中
    bootstrap栅格系统
    MVC框架
    类模板
    c++编译器模板机制剖析
    函数模板与函数重载
    函数模板当参数强化
    泛型编程—函数模板
    用友GRP-u8 注入-RCE漏洞复现
    漏洞代码调试(二):Strtus2-001代码分析调试
  • 原文地址:https://www.cnblogs.com/binggo2020/p/6696962.html
Copyright © 2011-2022 走看看