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
'Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Swift ์๊ณ ๋ฆฌ์ฆ์ ์ฐ์ด๋ ๋ฌธ๋ฒ ์ ๋ฆฌ (0) | 2020.07.07 |
---|---|
Swift String to Array (component) (0) | 2020.07.03 |
Swift ์ฝ๋ฉ ํ ์คํธ ์ค๋น - Java to Swift ๐ฑ (1) | 2020.07.01 |
์ค์ํํธ 101 - Objects and Classes (0) | 2020.03.26 |
์ค์ํํธ 101 - ์๊ฐ (0) | 2020.03.25 |
๋๊ธ