Leetcode 2255. Count Prefixes of a Given String
You are given a list of strings words and a string s. A string is called a prefix of s if it can be obtained by removing some (possibly zero) characters from the end of s.
Return the number of strings in words that are prefixes of s.
words and the length of the string s?
words, and the length of each string and s could be up to 1000 characters.s means it matches the first part of s exactly.Initialization: Initialize a counter to zero to count the number of valid prefix strings in words.
Loop Through words: Iterate over each string in words.
Check Prefix: For each string, check if it is a prefix of s by using the startsWith method in Java.
Update Counter: If it is a prefix, increment the counter.
Return the Counter: Once all strings in words are checked, return the counter as the result.
class Solution {
public int countPrefixes(String[] words, String s) {
int count = 0;
for (String word : words) {
if (s.startsWith(word)) {
count++;
}
}
return count;
}
}
words: O(n) where n is the number of strings in words.startsWith method is O(m) where m is the length of the prefix being checked.n is the number of strings in wordsm is the average length of the stringsGiven the constraints, this approach will be efficient and handle the maximum input sizes effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?