• LeetCode #20 Valid Parentheses


    LeetCode #20 Valid Parentheses

    Question

    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.

    Solution

    Approach #1

    public class ListNode<T> {
        
        public var val: T
        public var next: ListNode?
        
        public init(_ val: T) {
            self.val = val
            self.next = nil
        }
    }
    
    public class Stack<T> {
        
        public var head: ListNode<T>?
        
        public func peek() -> T? {
            return head?.val
        }
        
        public func push(_ val: T) {
            let node = ListNode(val)
            node.next = head
            head = node
        }
        
        public func pop() -> T? {
            let t = head?.val
            head = head?.next
            return t
        }
    }
    
    class Solution {
        func isValid(_ s: String) -> Bool {
            var list = Stack<Character>()
            for c in s.characters {
                switch c {
                case "(":
                    list.push(")")
                case "{":
                    list.push("}")
                case "[":
                    list.push("]")
                default:
                    if list.pop() != c { return false }
                }
            }
            return list.head == nil
        }
    }
    

    Time complexity: O(n).

    Space complexity: O(n).

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7065607.html

  • 相关阅读:
    统计单词数 OpenJ_Bailian
    整数划分 NBUT
    高精度(x ,/, +, -, %)良心模板
    binary-tree-maximum-path-sum
    2080 特殊的质数肋骨 USACO (深度优先搜索)
    1413 权势二进制
    POJ 1258
    poj 3126
    hdu 1195
    POJ 3752
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/7065607.html
Copyright © 2020-2023  润新知