LeetCode 2255: Count Prefixes of a Given String Solution
Master LeetCode problem 2255 (Count Prefixes of a Given String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we iterate through each word in the input words array and check if the word is a prefix of the given string s. We can do this by comparing each character of the word with the corresponding character in s. If at any point the characters do not match, we break out of the loop. If we reach the end of the word and all characters match, we increment a counter to keep track of the number of words that are prefixes of s.
Algorithm:
- Initialize a counter variable
prefixCountto 0. - Iterate through each word in the
wordsarray. - For each word, compare each character with the corresponding character in
s. - If all characters match up to the length of the word, increment
prefixCount. - Return the final
prefixCount.
Time Complexity: O(n*m), where n is the number of words and m is the maximum length of a word in the words array.
Space Complexity: O(1)
Solution Code
class Solution {
public int countPrefixes(String[] words, String s) {
int prefixCount = 0;
for (String word : words) {
int i = 0;
while (i < word.length() && i < s.length() && word.charAt(i) == s.charAt(i)) {
i++;
}
if (i == word.length()) {
prefixCount++;
}
}
return prefixCount;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2255 (Count Prefixes of a Given String)?
This page provides optimized solutions for LeetCode problem 2255 (Count Prefixes of a Given String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2255 (Count Prefixes of a Given String)?
The time complexity for LeetCode 2255 (Count Prefixes of a Given String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2255 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2255 in Java, C++, or Python.