FastPrepFormat a Centered Paragraph in a Star Frame

Format a Centered Paragraph in a Star Frame

ZipRecruiter logoZipRecruiter● MediumNEW GRADOA
Learn

Problem statement

Join sentences with one space, split on whitespace, and greedily pack words into content lines of at most width characters using one space between words. Every word fits within width.

Return a frame whose top and bottom are width + 2 stars. Each content row has side stars and exactly width interior characters. Center a line with spaces; when the unused count is odd, put the extra space on the right. If there are no words, emit one empty centered content row.

Function

frameParagraph(sentences: String[], width: int) → String[]

Examples

Example 1

sentences = ["hello world from zip"]width = 10return = ["************","*  hello   *","*world from*","*   zip    *","************"]

Words are greedily packed and each line centered.

Example 2

sentences = ["abc"]width = 6return = ["********","* abc  *","********"]

The extra odd space is placed on the right.

Constraints

  • 1 <= width <= 1000
  • The total sentence length is at most 100000.

More ZipRecruiter problems

See ZipRecruiter hiring insights
public String[] frameParagraph(String[] sentences, int width) {
    // Write your code here.
}
sentences["hello world from zip"]
width10
expected["************", "* hello *", "*world from*", "* zip *", "************"]
Checking account…