Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.

I. Problem description

You are given an array of strings words and a string pref that returns the number of strings prefixed with pref in words **.

The prefix of the string s is any leading consecutive string of S.

Title link: Counts the string containing the given prefix

Two, the title requirements

Sample 1

Input: words = ["pay","attention","practice","attend"], pref = "at" "Attention" and "attend".Copy the code

The sample 2

Input: words = ["leetcode","win","loops","success"], pref = "code" Output: 0 Description: There is no string prefixed with "code".Copy the code

inspection

1. String application 2. You are advised to use 10 to 25 minutesCopy the code

Third, problem analysis

This problem is relatively simple, we can use the C++ String class lookup method to solve this problem.

function usage
Find (returns element location on success, -1 on failure)
s.find(‘A’) Find character A
s.find(“ABC”) Find the string ABC
s.find(‘A’,2) Look for character A starting at position 2
S. ind (” ABCD “, 1, 2) Starting at position 1, look for the first two characters of ABCD
s.rfind() Start at the end of the string
If words[I].find(pref)==0, pref is the prefix of words[I].Copy the code

String = String = String = String = String = String = String

Four, coding implementation

class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int i,ans=0,n=words.size(a);/ / initialization
        for(i=0; i<n; i++)// loop judgment
        {
            if(words[i].find(pref)==0)// Check whether it is a prefix
            {
                ans++;// counter ++}}return ans;// Output the result}};Copy the code

V. Test results