๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Swift

[๐Ÿ—‚ Swift Data Structure] - Stack

by HaningYa 2020. 6. 25.
728x90
public struct Stack<Element> {
    private var storage : [Element] = []
    public init(){}
    public init(_ element: [Element]){
        storage = element
    }
}
extension Stack: CustomStringConvertible{
    public var description:String{
        """
        --top--
        \(storage.map{"\($0)"}.reversed().joined(separator: "\n"))
        ------
"""
    }
    public mutating func push(_ element: Element){
        storage.append(element)
    }
    @discardableResult
    public mutating func pop() -> Element?{
        storage.popLast()
    }
    public func peek() -> Element?{
        storage.last
    }
    public var isEmpty: Bool{
        peek() == nil
    }
    
}
//Q1
func printInReverse<T>(_ array:[T]){
    var stack = Stack(array)
    while let value = stack.pop(){
        print(value)
    }
    
}
var array = [1,2,3,4,5,6,7,8,9,10]
printInReverse(array)

//Q2
func checkParentheses(_ string : String) -> Bool {
    var stack = Stack<Character>()
    
    for character in string{
        if character == "(" {
            stack.push(character)
        }else if character == ")"{
            if stack.peek() == "("{
                stack.pop()
            }else{
                stack.push(character)
            }
        }
    }
    return stack.isEmpty
}
let str1 = "h((e))llo(world)()"
let str2 = "(hello world))"
print(checkParentheses(str1))
print(checkParentheses(str2))


728x90

๋Œ“๊ธ€