Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/2255.html
2255. Count Prefixes of a Given String (Easy)
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.
A 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 <= 10001 <= words[i].length, s.length <= 10words[i]andsconsist of lowercase English letters only.
Similar Questions:
- Check If a Word Occurs As a Prefix of Any Word in a Sentence (Easy)
- Check If String Is a Prefix of Array (Easy)
- Counting Words With a Given Prefix (Easy)
Solution 1.
-
class Solution { public int countPrefixes(String[] words, String s) { int ans = 0; for (String word : words) { if (word.equals(s.substring(0, Math.min(s.length(), word.length())))) { ++ans; } } return ans; } } -
class Solution { public: int countPrefixes(vector<string>& words, string s) { int ans = 0; for (auto& word : words) if (s.substr(0, word.size()) == word) ++ans; return ans; } }; -
class Solution: def countPrefixes(self, words: List[str], s: str) -> int: return sum(word == s[: len(word)] for word in words) -
func countPrefixes(words []string, s string) int { ans := 0 for _, word := range words { if strings.HasPrefix(s, word) { ans++ } } return ans } -
function countPrefixes(words: string[], s: string): number { return words.filter(w => s.startsWith(w)).length; }