Beats 100% | String Matching | Solution for LeetCode#2185
IntuitionThe problem asks to count the number of strings in an array that start with a given prefix. The intuitive approach is to check each string in the array
![image.png](https://assets.leetcode.com/users/images/c832a2d6-c45a-408c-a7a6-33899e66174b_1736381035.5194995.png)

# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem asks to count the number of strings in an array that start with a given prefix. The intuitive approach is to check each string in the array against the prefix.

# Approach
<!-- Describe your approach to solving the problem. -->
1. Iterate through each word in the words array.
2. For each word, use the startsWith() method to check if it begins with the given pref.
3. If a word starts with pref, increment a counter.
4. After checking all words, return the final count.

# Complexity
- Time complexity: O(n * m), where n is the number of words in the array and m is the average length of the words
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public int prefixCount(String[] words, String pref) {
        int n=words.length;
        int cnt=0;

        for(int i=0; i<n; i++){
            if(words[i].startsWith(pref)){
                cnt++;
            }
        }

        return cnt;
    }
}
```
```python []
class Solution(object):
    def prefixCount(self, words, pref):
        """
        :type words: List[str]
        :type pref: str
        :rtype: int
        """
        
        n=len(words)
        cnt=0
        for i in range(n):
            if words[i].startswith(pref):
                cnt+=1
        
        return cnt
```
```cpp []
#include <vector>
#include <string>

class Solution {
public:
    int prefixCount(const std::vector<std::string>& words, const std::string& pref) {
        int cnt = 0;
        for (const auto& word : words) {
            if (word.rfind(pref, 0) == 0) { // Checks if 'pref' is a prefix of 'word'
                cnt++;
            }
        }
        return cnt;
    }
};

```
```swift []
class Solution {
    func prefixCount(_ words: [String], _ pref: String) -> Int {
        var count = 0
        for word in words {
            if word.hasPrefix(pref) {
                count += 1
            }
        }
        return count
    }
}

```
['String', 'Swift', 'Python', 'C++', 'Java', 'Python3']