17.9 design a method to find out how often any given word appears in a book.
Solution:
1 One-time query
Iterate through each word of the book to calculate the number of occurrences of a given word. Time complexity O (n), we cannot continue to optimize it because every single time in the book needs to be accessed once. Of course, if we assume that the words in the book are evenly distributed, then we can just count the number of occurrences of the first half of the book, multiply it by 2, or just count the number of occurrences of the first One-fourth books, then multiply by 4.
2 Multiple queries
If we want to execute the query repeatedly, it might be worthwhile to spend more time, spend more memory, and preprocess the book. We can construct a hash table that maps the word to how often it appears. In this way, the frequency of any word can be found in the O (1) time, the specific code is as follows:
#include <string>#include<map>#include<iostream>using namespaceStd;map<string,int> Setupdictionary (stringBook[],intN) { inti; Map<string,int>MP; for(i=0; i<n;i++) {Mp[book[i]]++; } returnMP;}intGetfrequency (map<string,int> &MP,strings) { returnmp[s];}intMain () {stringstr[Ten]={"a","b","a","C","D","D","e","F","e","e"}; Map<string,int> mp=setupdictionary (str,Ten); cout<<getfrequency (MP,"a") <<Endl;}
careercup-Medium Difficulty 17.9