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
            
        }
    }
    
  • 相关阅读:
    postgresql字符串函数
    ruby中的设计模式--策略模式
    (转)MySQL 性能优化的最佳20多条经验分享
    (转)ruby中的设计模式--模板方法
    观察者模式的应用
    postgresql的ARRAY_TO_STRING
    ruby和javascript的观察者模式
    mysql表连接的时候注意事项
    checkbox记忆功能的实现
    order by的注意事项
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12734654.html
Copyright © 2011-2022 走看看