Problem overview
The function wordFrequency receives a sentence, a string of lowercase words separated by single spaces, and returns a dictionary that maps each word to how many times it appears. The sentence has at least one word, and the order of the entries doesn't matter.
For "the cat and the hat" the answer has four entries: "the" is 2, and "cat", "and" and "hat" are 1 each.
Approach: split, then count
The problem has two parts. First, cut the sentence into words. Then count them with a dictionary, the same way you would count letters: a word that is already a key gets its count increased, and a new word starts at 1.
Splitting is done with split(separator: " "), which cuts the string at every space and returns the pieces between the spaces.
Step by step
- Split the sentence with
sentence.split(separator: " ")and keep the result in aletnamedwords. - Create
countsas an empty[String: Int]withvar. - Loop over the pieces with
for piece in words. - Convert the piece to a
StringwithString(piece). - Bind the current count with
if let count = counts[word]and storecount + 1. - Start new words at 1 in the
elsebranch. - Return
countsafter the loop.
On "the cat and the hat" the split gives the pieces "the", "cat", "and", "the", "hat". The first "the" creates its entry with 1, "cat" and "and" do the same, the second "the" finds the entry and raises it to 2, and "hat" is new. The loop ends with the four entries listed above.
The pattern is the same one used to count letters. Only the thing being counted changed: pieces of a split instead of characters of a string.
The solution in Swift
class Solution {
func wordFrequency(_ sentence: String) -> [String: Int] {
let words = sentence.split(separator: " ")
var counts = [String: Int]()
for piece in words {
let word = String(piece)
if let count = counts[word] {
counts[word] = count + 1
} else {
counts[word] = 1
}
}
return counts
}
}
Swift details
splitreturns substrings. The type ofsentence.split(separator: " ")is[Substring]. ASubstringis a view into the original string, not aString, and the dictionary's keys areString. That is why each piece goes throughString(piece)before it is used as a key.- The separator is a character.
" "insplit(separator: " ")is read as a singleCharacter, so it matches each space. - Optional lookup.
counts[word]is anInt?,nilfor a word that hasn't been seen.if letruns its body only when a count exists, and theelsebranch handles the first sighting. - Dictionaries are unordered. The entries can print in any order, and the order can differ between runs.
Edge cases and common mistakes
- Repeated word.
"go go go"gives a single key, "go", with the value 3. - One word.
"hello"gives one entry, "hello": 1. - Extra spaces. The lesson promises single spaces. With two spaces in a row,
split(separator: " ")still drops the empty piece between them:"a b".split(separator: " ")gives["a", "b"]. PassingomittingEmptySubsequences: falsewould keep it, giving["a", "", "b"], and the empty string would then be counted as a word. - Forgetting to convert. Using the
Substringdirectly as a key of a[String: Int]dictionary doesn't compile: the compiler reports that it cannot convert a value of typeSubstringto the expected argument typeString. - Counting the pieces in a loop but reading
counts[word]as a plain number. It is an optional until you unwrap it.
Testing
Entries are listed in alphabetical order here for readability.
"the cat and the hat"gives and: 1, cat: 1, hat: 1, the: 2."go go go"gives go: 3."hello"gives hello: 1.
