Top Ten Most Frequent Words in a Book
Problem statement
You are given a string text containing a book. A word is a maximal consecutive sequence of English letters A-Z or a-z. Every other character, including a digit, is a delimiter. Matching is case-insensitive, so normalize every word to lowercase.
Return at most ten entries in the form "word frequency", ordered by descending frequency. Break equal-frequency ties lexicographically by normalized word. If fewer than ten distinct words occur, return every distinct word. If no words occur, return an empty array.
Function
topTenWords(text: String) → String[]Examples
Example 1
text = "Red blue red GREEN blue red"return = ["red 3","blue 2","green 1"]Case variants are merged. Only three distinct normalized words occur.
Example 2
text = "k j i h g f e d c b a"return = ["a 1","b 1","c 1","d 1","e 1","f 1","g 1","h 1","i 1","j 1"]All eleven words tie, so lexical order selects the first ten and excludes k.
Example 3
text = "Go2GO go42lang LANG9"return = ["go 3","lang 2"]Digits split words: Go2GO contributes two occurrences of go, and go42lang contributes go and lang.
Constraints
1 <= text.length <= 1000000textcontains printable ASCII characters and whitespace.