Disappearing Pairs
heydoy opened this issue · comments
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ S : inout String) -> String {
// write your code in Swift 4.2.1 (Linux)
var result = ""
for item in S {
if result.last == item {
_ = result.popLast()
} else {
result.append(item)
}
}
return result
}
배열은 removeLast()
나popLast()
를 이용해 제거할 수 있다. 둘은 동일하게 동작하지만 pop의 경우 배열이 비었을 때 사용하면 nil을 반환한다. 문자열은 캐릭터의 배열 형태이므로 append
나 popLast
메서드를 사용할 수 있다.
위 문제는 스택 특징을 이용해 풀었기 때문에 pop 메서드를 이용했다. 이전 문자와 현재 문자가 동일할 경우 이전문자를 없앤다.