https://www.acmicpc.net/problem/6137
6137번: 문자열 생성
첫 번째 줄에 문자열 S의 길이 N이 주어진다. (N <= 2,000) 이후 N개의 줄에 S를 이루는 문자들이 주어진다.
www.acmicpc.net
투포인터 문제다.
풀이

시작을 나타내는 인덱스 head, 끝을 나타내는 인덱스 tail을 생성하여 각각 0과 n-1을 부여. (head <= tail)인 순간까지 문자열 S를 탐색한다. 매 반복문마다 더 먼저 오는 문자를 출력할 문자열에 더해주고 해당 인덱스를 증가시킨다.

head와 tail이 가리키는 문자가 같다면, head ~ tail 범위의 문자열과 역순의 문자열을 비교하여 순서가 먼저인 문자열 측의 문자를 추가하면 된다.
80자마다 줄 바꿈 "\n"을 출력해야 한다는 점을 잊지 말자. 본인의 경우 문자열에 "\n"을 추가한 뒤 마지막에 한 번에 출력하게끔 코드를 작성했는데, "\n" 문자열도 포함돼서 카운트하는 바람에 오답판정을 받았다.
정답 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let n = Int(readLine()!)! | |
var arr = [String]() | |
var ans = "" | |
for _ in 0..<n{ arr.append(readLine()!) } | |
var head = 0 | |
var tail = n-1 | |
var cnt = 0 | |
while head <= tail{ | |
if cnt%80==0 && cnt>0{ ans.append("\n") } | |
if head == tail{ | |
ans.append(arr[head]) | |
break | |
} | |
if arr[tail] < arr[head]{ | |
ans.append(arr[tail]) | |
tail -= 1 | |
}else if arr[tail] == arr[head]{ | |
let h = arr[head...tail].joined() | |
let t = String(h.reversed()) | |
if h<=t{ | |
ans.append(arr[head]) | |
head += 1 | |
}else{ | |
ans.append(arr[tail]) | |
tail -= 1 | |
} | |
}else{ | |
ans.append(arr[head]) | |
head += 1 | |
} | |
cnt += 1 | |
} | |
print(ans) |

'Problem Solving > BOJ' 카테고리의 다른 글
[15831] 준표의 조약돌 (0) | 2023.01.23 |
---|---|
[12892] 생일 선물 (0) | 2023.01.21 |
[22862] 가장 긴 짝수 연속한 부분 수열 (large) (0) | 2023.01.19 |
[1484] 다이어트 (0) | 2023.01.18 |
[2118] 두 개의 탑 (0) | 2023.01.17 |