Count Repeated Word Occurrences
Problem statement
Given paragraph, count repeated word occurrences.
A word is a maximal consecutive run of English letters A-Z or a-z. Every other character separates words. Matching ignores case.
The first occurrence of a word contributes 0. Every later occurrence of that word contributes 1. Return the total over the paragraph. A word appearing c times contributes c - 1.
Return 0 when there are no words. Count repeated occurrences rather than the number of distinct repeated words.
Function
countWordRepetitions(paragraph: String) → intExamples
Example 1
paragraph = "The sun is the largest object in the solar system. It is the only star. And the sun is bright."return = 7the appears five times and contributes 4. is appears three times and contributes 2. sun appears twice and contributes 1. Every other word appears once, so the total is 4 + 2 + 1 = 7.
Example 2
paragraph = "hello world text, text hello, text"return = 3hello appears twice and contributes 1. text appears three times and contributes 2. world contributes nothing, so the answer is 3.
Example 3
paragraph = "Blue blue BLUE, red red."return = 3Matching ignores case. The three occurrences of blue contribute 2, and the two occurrences of red contribute 1. The answer counts repeated occurrences, so it is 3; counting distinct repeated words would give 2.
Constraints
0 <= paragraph.length <= 20000- Every character is printable ASCII, a tab, a carriage return, or a line feed.