문제
풀이 코드
// 변수 선언
var inputs = readLine()!
var commandResult = ""
let commandCount = Int(readLine()!)!
for _ in 0..<commandCount {
let command = readLine()!
switch command {
case "L":
if !inputs.isEmpty { commandResult.append(inputs.popLast()!) }
case "D":
if !commandResult.isEmpty { inputs.append(commandResult.popLast()!) }
case "B":
if !inputs.isEmpty { inputs.removeLast() }
default:
inputs.append(command.last!)
}
}
print(inputs + commandResult.reversed())
풀이 과정
// 변수 선언
var result = readLine()!
let commandCount = Int(readLine()!)!
var cursor = result.count
for _ in 0..<commandCount {
let index = result.index(result.startIndex, offsetBy: cursor)
let command = readLine()!.split(separator: " ")
switch command[0] {
case "P":
result.insert(contentsOf: command[1], at: index)
cursor += 1
case "L":
if cursor - 1 >= 0 { cursor -= 1 }
case "D":
if cursor + 1 <= result.count { cursor += 1 }
default:
if cursor > 0 {
cursor -= 1;
let removeIndex = result.index(result.startIndex, offsetBy: cursor)
result.remove(at: removeIndex) }
}
}
print(result)
처음, 위와 같은 방식으로 문제를 풀었다, 하지만 시간초과 가 발생했습니다.
이리 저리 고쳐 봤지만, 시간 초과 문제를 해결하지 못했습니다.
그래서 검색해본 결과
- split을 쓰면 시간이 오래걸림
- 내가 짠 코드에서 String.index 로 변환하고, 다시 변수 생성하고 등등의 과정으로 오랜 시간이 소요됨
이라는 결론을 낼 수 있었고, Stack 구조체를 이용하여 풀어야 한다고 생각했지만,
그런데 전에 풀었던 방식으로 구조체로 사용하게되면 string 을 각각 문자로 변환하고 그걸 또 스택에 넣어야 하는 과정속에서 또 다시 시간초과가 날 거 같아서 그냥 배열로 처리를 해주었습니다.
입력된 결과에서 현 커서의 위치가 이동될 때 마다 새로운 문자열(commandResult)에 Push 해 주거나 원 문자열에서 pop 해주면서 계산해주어 풀이했습니다.