careercup-Medium Difficulty 17.9

Source: Internet
Author: User

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> &AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.