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

posted on 2017-06-22 17:08  Silence_cnblogs  阅读(212)  评论(0编辑  收藏  举报