문제 출처 : https://www.acmicpc.net/problem/18322
언어 : Kotlin
문제 설명 :
Bessie the cow is working on an essay for her writing class. Since her handwriting is quite bad, she decides to type the essay using a word processor.
The essay contains N words (1 ≤ N ≤ 100), separated by spaces. Each word is between 1 and 15 characters long, inclusive, and consists only of uppercase or lowercase letters. According to the instructions for the assignment, the essay has to be formatted in a very specific way: each line should contain no more than K (1 ≤ K ≤ 80) characters, not counting spaces. Fortunately, Bessie's word processor can handle this requirement, using the following strategy:
- If Bessie types a word, and that word can fit on the current line, put it on that line.
- Otherwise, put the word on the next line and continue adding to that line.
Of course, consecutive words on the same line should still be separated by a single space. There should be no space at the end of any line.
Unfortunately, Bessie's word processor just broke. Please help her format her essay properly!
입력 :
The first line of input contains two space-separated integers N and K.
The next line contains N words separated by single spaces. No word will ever be larger than K characters, the maximum number of characters on a line.
출력 :
Bessie's essay formatted correctly.
제한 사항 :
- 시간 제한 : 2초
- 메모리 제한 : 512MB
입출력 예 :
입력 | 출력 |
10 7 hello my name is Bessie and this is my essay |
hello my name is Bessie and this is my essay |
풀이 :
현재 길이와 추가될 단어 길이가 k보다 크면 새로운 줄에 단어를 추가하고 아니라면 단어를 출력한다.
출력할때 단어 사이의 공백은 유지되어야 하므로 현재 길이가 0 이상일때 단어 추가시 마다 공백을 추가한다.
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
val bw = BufferedWriter(OutputStreamWriter(System.out))
val (n, k) = readLine().split(" ").map { it.toInt() }
val words = readLine().split(" ")
var curLength = 0
for (word in words) {
if (curLength + word.length > k) {
bw.newLine()
bw.write(word)
curLength = word.length
} else {
if (curLength > 0) {
bw.write(" ")
}
bw.write(word)
curLength += word.length
}
}
bw.flush()
bw.close()
}
'백준 > 문제' 카테고리의 다른 글
16900번: 이름 정하기 (0) | 2024.08.16 |
---|---|
5636번: 소수 부분 문자열 (0) | 2024.08.15 |
1599번: 민식어 (0) | 2024.08.14 |
3778번: 애너그램 거리 (0) | 2024.08.14 |
28255번: 3단 초콜릿 아이스크림 (0) | 2024.08.13 |
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!