Problem · String

Prepare Notification

Learn this problem
EasyMicrosoftFULLTIMEOA
See Microsoft hiring insights

Problem statement

Prepare a notification of the given message which will be displayed on a mobile device. The message is made of words separated by single spaces. The length of the notification is limited to K characters. If the message is too long to be displayed fully, some words from the end of the message should be cropped, keeping in mind that:

  • the notification should be as long as possible;
  • only whole words can be cropped;
  • if any words are cropped, the notification should end with "…"; the dots should be separated from the last word by a single space;
  • the notification may not exceed the K-character limit, including the dots.
  • If all the words need to be cropped, the notification is "..." (three dots without a space).

    Functin Description:

    Complete function prepareNotification in the editor.

    Function prepareNotification has the following parameters:

  • String message & int k
  • Returns:

  • The notification to display, which has no more than K chars, as described above.
  • Function

    prepareNotification(message: String, K: int) → String

    Examples

    Example 1

    message = "And now here is my secret"K = 15return = "And now ..."
    "And now ..." is the longest notification that keeps whole words, includes the required space before the dots, and stays within 15 characters. "And now here ..." would be 16 characters long.

    Example 2

    message = "There is an animal with four legs"K = 15return = "There is an ..."
    "There is an ..." is exactly 15 characters long, including the space and the three dots.

    Example 3

    message = "super dog"K = 4return = "..."
    The function should return "...".

    Example 4

    message = "how are you"K = 20return = "how are you"
    The function should return "how are you".

    Constraints

  • K is an integer within the range [3..500]
  • the length of string message is within the range [1..500]
  • string message is made of English letters (a-z, 'A-Z) and spaces
  • message does not contain spaces at the beginning or at the end
  • words are separated by a single space (there are never two or more consecutive spaces)
  • More Microsoft problems

    drafts saved locally
    public String prepareNotification(String message, int K) {
        // write your code here
    }
    
    message"And now here is my secret"
    K15
    expected"And now ..."
    checking account