65. Headline Case

A newsroom tool formats headlines. The title is a list of words separated by single spaces, written with any mix of upper and lower case letters. Rewrite it in headline case using these rules:

the first word and the last word always start with a capital letter; any other word that is one of a, an, the, and, or, of, in, on, to, at, by, for (compared ignoring case) is written fully in lower case; every remaining word starts with a capital letter and has all its other letters in lower case.

Return the formatted headline, keeping single spaces between words.

Example 1

Input:
title = "the lord of the rings"
Output:
"The Lord of the Rings"
Explanation:

The first word is capitalised, of and the in the middle stay lower case, and the remaining words are capitalised.

Example 2

Input:
title = "a tale TO remember"
Output:
"A Tale to Remember"
Explanation:

A is the first word so it is capitalised, TO is a small word in the middle so it becomes to, and the rest are capitalised.

Constraints

1 ≤ title.length ≤ 104

title contains English letters and single spaces, with no leading or trailing space

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…