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
            
        }
    }
    
  • 相关阅读:
    【转】ListView,GridView之LayoutAnimation特殊动画的实现 ps:需要学习的是在getView中添加动画的思想
    自定义Dialog
    android 横向list特效——规格滑动
    android BaseAdapter优化
    自定义弧形进度条
    滑块闹钟界面
    HTML学习10
    HTML学习9
    HTML学习8
    HTML学习7
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12734654.html
Copyright © 2011-2022 走看看