zoukankan      html  css  js  c++  java
  • Valid Parentheses

    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.

    思路:

      经典栈的应用

    我的代码:

    public class Solution {
        public boolean isValid(String s) {
            if(s == null || s.length() == 0) return true;
            Stack<Character> stack = new Stack<Character>();
            for(int i = 0; i < s.length(); i++)
            {
                char c = s.charAt(i);
                if(isRight(c))
                {
                    if(stack.isEmpty()) return false;
                    char left = stack.pop();
                    if(!isMatch(left,c)) return false;
                }
                else
                {
                    stack.push(c);
                }
            }
            return stack.isEmpty();
        }
        public boolean isMatch(char left, char right)
        {
            if((left=='('&&right==')')||(left=='['&&right==']')||(left=='{'&&right=='}'))   return true;
            return false;
        }
        public boolean isRight(char c)
        {
            if(c == ')' || c == ']' || c == '}')    return true;
            return false;
        }
    }
    View Code
  • 相关阅读:
    两排滚动js
    弹性布局
    channelartlist添加栏目链接
    首页调取二级、三级栏目
    dede完美分页样式
    如何安装sass
    首页分页(自由列表)
    tag标签调取
    25.简单的路由
    24.简单的自定义服务
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4336041.html
Copyright © 2011-2022 走看看