zoukankan      html  css  js  c++  java
  • leetcode刷题笔记二十 有效的括号 Scala版本

    leetcode刷题笔记二十 有效的括号 Scala版本

    源地址:20. 有效的括号

    问题描述:

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true
    

    代码补充:

    //本题是一个典型的栈的应用,遇到左侧括号则入栈,遇到右侧括号有两种可能性,栈空或者出栈的括号与右侧入栈括号未能对应返回false
    import scala.collection.mutable.Stack
    object Solution {
        def isValid(s: String): Boolean = {
            if ( s == "") return true
            val stack = Stack[Char]()
            for (elem <- s){
                elem match {
                    case '(' => stack.push(elem)
                    case '[' => stack.push(elem)
                    case '{' => stack.push(elem)
                    case ')' => if (stack.length == 0 || stack.pop != '(') return false
                    case ']' => if (stack.length == 0 || stack.pop != '[') return false
                    case '}' => if (stack.length == 0 || stack.pop != '{'  ) return false
                    case _ => return false
                }
            } 
            //如果左侧括号入栈仍有剩余未匹配,则false
            if (stack.length == 0) return true
            else return false
            
        }
    }
    
  • 相关阅读:
    27 mysql主从出现错误
    Spring各个jar包作用
    SpringBoot 的启动banner生成网址
    Joda-Time 简介
    IDEA配置GIT
    iView 发布后台管理系统 iview-admin
    Springboot的默认定时任务——Scheduled注解
    如何使用java validation api进行参数校验----Hibernate-Validation
    Vue的安装及使用快速入门
    springboot整合shiro应用
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12734654.html
Copyright © 2011-2022 走看看