티스토리 뷰
오늘 리뷰할 문제는 68.text justification 입니다. https://leetcode.com/problems/text-justification/
Text Justification - LeetCode
Can you solve this real interview question? Text Justification - Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words i
leetcode.com
문제 설명을 하자면
단어들의 리스트와, 최대길이가 주어졌을 때, 해당 단어들을 규칙에 따라 최대길이를 넘지 않게 배치시키는 알고리즘을 작성하는 것이다.
규칙을 나열해보자면
1. 단어 사이에는 최소한 한개의 간격이 존재해야 한다.
2. 다음단어가 들어가지 못하는 경우, 빈 공간은 단어 사이의 공간에 최대한 균일하게 분배해야 한다. 균일하게 분배하는게 어렵다면, 앞쪽 공백부터 채운다.
3. 마지막 줄은 공백을 사이에 채우지 않는다.
simulation을 해야만 되기 때문에, 단어 목록을 앞에서부터 순회하면서 결과를 만들도록 구현했다.
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
results = []
current_words = []
current_min_length = 0
def words_to_string(target_words: List[str]) -> str:
if len(target_words) == 1:
return f"{target_words[0]}{' ' * (maxWidth - len(target_words[0]))}"
num_space = len(target_words) - 1
space_length = maxWidth - sum(len(w) for w in target_words)
default_space = space_length // num_space
extra_space = space_length % num_space
result_string = ""
for i, w in enumerate(target_words):
result_string += w
if i != len(target_words) - 1:
result_string += " " * default_space
if extra_space:
result_string += " "
extra_space -= 1
return result_string
for word in words:
if len(current_words) == 0:
expected_min_length = current_min_length + len(word)
else:
expected_min_length = current_min_length + len(word) + 1
if expected_min_length > maxWidth:
results.append(words_to_string(current_words))
current_words = []
current_min_length = len(word)
else:
current_min_length = expected_min_length
current_words.append(word)
if current_words:
results.append(
" ".join(current_words) + " " * (maxWidth - current_min_length)
)
return results
assert Solution().fullJustify(
["This", "is", "an", "example", "of", "text", "justification."], 16
) == [
"This is an",
"example of text",
"justification. ",
]
assert Solution().fullJustify(
["What", "must", "be", "acknowledgment", "shall", "be"], 16
) == [
"What must be",
"acknowledgment ",
"shall be ",
]
assert Solution().fullJustify(
[
"Science",
"is",
"what",
"we",
"understand",
"well",
"enough",
"to",
"explain",
"to",
"a",
"computer.",
"Art",
"is",
"everything",
"else",
"we",
"do",
],
20,
) == [
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do ",
]
20분정도 투자했더니, 위의 구현이 나왔고, 제출결과는 다음과 같았다.
다른 사람의 코드를 봤을 때, 알고리즘은 큰 차이는 없어보였다.
'개발 > 알고리즘' 카테고리의 다른 글
[leetcode 매일 풀기] 85. maximum rectangle (0) | 2023.12.10 |
---|---|
[leetcode 매일 풀기] 76. minimum window substring (1) | 2023.12.09 |
[leetcode 매일 풀기] 65. valid number (0) | 2023.12.07 |
[leetcode 매일 풀기] 60 permutation sequence (2) | 2023.12.06 |
[leetcode 매일풀기] 52. n queens 2 (1) | 2023.12.05 |
- Total
- Today
- Yesterday
- 회고
- maximum rectangle
- hard mode challenge
- valid number
- wildcard matching
- best time to buy and sell stock 3
- leetcode 매일 풀기
- text justification
- first missing positive
- otel
- longest valid parentheses
- distinct subsequences
- leetcode
- datalakehouse
- 글또 10기
- leetcode 매일풀기
- word ladder 2
- binary tree maximum path sum
- scramble string
- slay the spire에 진심인편
- Python
- permutation sequence
- 개발자 글쓰기
- 가상면접 사례로 배우는 대규모 시스템 설계
- mlse
- sudoku solver
- palindrome partitioning 2
- n queens 2
- substring with concatenation of all words
- 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |