Count Prefixes of a Given String LeetCode Solution

Problem – Count Prefixes of a Given String LeetCode Solution

You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.

Return the number of strings in words that are a prefix of s.

prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.

Example 1:

Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.

Example 2:

Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s. 
Note that the same string can occur multiple times in words, and it should be counted each time.

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, s.length <= 10
  • words[i] and s consist of lowercase English letters only.

Count Prefixes of a Given String LeetCode Solution in Java

    public int countPrefixes(String[] words, String s) {
        int res = 0;
        for (String w : words)
            if (s.startsWith(w))
                res++;
        return res;
    }

Count Prefixes of a Given String LeetCode Solution in C++

    int countPrefixes(vector<string>& words, string s) {
        int res = 0;
        for (auto& w : words)
            res += s.find(w) < 1;
        return res; 
    }

Count Prefixes of a Given String LeetCode Solution in Python

    def countPrefixes(self, words, s):
        return sum(map(s.startswith, words))
Count Prefixes of a Given String LeetCode Solution Review:

In our experience, we suggest you solve this Count Prefixes of a Given String LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Count Prefixes of a Given String LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Count Prefixes of a Given String LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.